Consider the following code:
1fruits = ["orange","grape","banana"]2one,two,three = fruits3print(one)4print(two)5print(three)
When you want to destruct a list in Python and assign it to individual variables, you can do it like the above. The above code will run fine and will print the following output:
1orange2grape3banana
But if the number of variables on the left side is less than that of the right side, as shown below:
1fruits = ["orange","grape","banana"]2one,two = fruits3print(one)4print(two)
You will get the following error:
1Traceback (most recent call last):2 File "main.py", line 2, in <module>3 one,two = fruits4ValueError: too many values to unpack (expected 2)
To fix the error, ensure that the number of variables on the left side is equal to the number of elements in the list on the right side.
If you want only the first 2 elements of the list, you can do it like this:
1fruits = ["orange","grape","banana"]2one,two = fruits[:2]3print(one)4print(two)
Do follow me on twitter where I post developer insights more often!
Leave a Comment