ValueError: too many values to unpack (expected 2)
What it means
You wrote several names on the left of =, like a, b = ..., and the value on the right held more items than there are names. Python needs exactly one name per item. The number in brackets is how many names you gave.
1. Splitting text into more parts than names
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> ValueError: too many values to unpack (expected 2)
The fix
Ana 31 London Ana ['31', 'London']
Three parts need three names. A starred name such as *rest collects any extra items into a list.
2. Looping over a dictionary without `.items()`
This raises the error
Traceback (most recent call last): File "<exec>", line 2, in <module> ValueError: too many values to unpack (expected 2)
The fix
Ana 90 Ben 85
Looping over a dictionary gives only its keys, so Python tries to unpack the string 'Ana' into two names, letter by letter. .items() gives (key, value) pairs.
3. A function returns more values than you unpack
This raises the error
Traceback (most recent call last): File "<exec>", line 4, in <module> ValueError: too many values to unpack (expected 2)
The fix
4 8 6.0
return a, b, c sends back a tuple of three values, so you need three names. Use _ for a value you do not need: low, high, _ = stats(...).
When you see this error, check
- Count the names on the left of
=and the items on the right. - Print the value you are unpacking, or its
len(). - Loop over
dict.items()when you want keys and values together. - Use
*restto collect extra items, or_for values you will ignore.
Related errors
All Python errors · How to read a traceback · Step through your code