Editor

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

Broken
record = 'Ana,31,London'
name, age = record.split(',')
print(name, age)
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
ValueError: too many values to unpack (expected 2)

The fix

Fixed
record = 'Ana,31,London'
name, age, city = record.split(',') # one name per part
print(name, age, city)
first, *rest = record.split(',') # or collect the extras
print(first, rest)
Output
Ana 31 London
Ana ['31', 'London']

Three parts need three names. A starred name such as *rest collects any extra items into a list.

Try fixing it yourself in the editor

2. Looping over a dictionary without `.items()`

This raises the error

Broken
scores = {'Ana': 90, 'Ben': 85}
for name, score in scores:
print(name, score)
Output
Traceback (most recent call last):
  File "<exec>", line 2, in <module>
ValueError: too many values to unpack (expected 2)

The fix

Fixed
scores = {'Ana': 90, 'Ben': 85}
for name, score in scores.items():
print(name, score)
Output
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.

Try fixing it yourself in the editor

3. A function returns more values than you unpack

This raises the error

Broken
def stats(nums):
return min(nums), max(nums), sum(nums) / len(nums)
low, high = stats([4, 8, 6])
print(low, high)
Output
Traceback (most recent call last):
  File "<exec>", line 4, in <module>
ValueError: too many values to unpack (expected 2)

The fix

Fixed
def stats(nums):
return min(nums), max(nums), sum(nums) / len(nums)
low, high, average = stats([4, 8, 6])
print(low, high, average)
Output
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(...).

Try fixing it yourself in the editor

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 *rest to collect extra items, or _ for values you will ignore.

All Python errors · How to read a traceback · Step through your code