Skip to content
python

Python: too many values to unpack [Solved]

Jul 8, 2023Abhishek EH1 Min Read
Python: too many values to unpack [Solved]

Consider the following code:

1fruits = ["orange","grape","banana"]
2one,two,three = fruits
3print(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:

1orange
2grape
3banana

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 = fruits
3print(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 = fruits
4ValueError: 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!

© 2024 CodingDeft.Com