Fix: ValueError: too many values to unpack
Exact message
ValueError: too many values to unpack (expected 2)
Quick answer
ValueError: too many values to unpack occurs when the right side of an unpacking assignment yields more items than the left side expects. Fix by adjusting the number of targets, using *rest to capture extras, or indexing the iterable directly.
Why this error happens
Python's tuple unpacking is strict: a, b = iterable requires exactly two values. If iterable has three or more items, it raises this ValueError. The error often appears when unpacking a list of dicts (each dict is one item, not its keys) or after refactoring a function to return more values.
Example: Wrong vs Right
Wrong
a, b = (1, 2, 3) # ValueError: too many values to unpack (expected 2)
Right
# Option 1: match the count a, b, c = (1, 2, 3) # Option 2: star to capture extras a, b, *rest = (1, 2, 3, 4, 5) # Option 3: index the items you want items = (1, 2, 3) a, b = items[0], items[1]
How to fix it (step by step)
- Print the right side's length or type before the assignment
- If a function returns more items than expected, either unpack all of them or index one
- Use *rest to accept extras without erroring
- If iterating a list of dicts, remember the dict itself is one item, not each key
Frequently asked questions
What does *rest do?
*rest captures the remaining items as a list. a, *rest = [1,2,3,4] gives a=1, rest=[2,3,4]. Only one starred target is allowed.
Why does for k, v in dict fail?
Iterating a dict yields keys, not pairs. Use dict.items() to iterate over (key, value) pairs.
What is 'not enough values to unpack'?
The opposite error — the iterable has fewer items than the targets expect. Same fixes apply in reverse.
Related Python errors
Need a fix for a different error?
Use the free to paste any traceback and get an AI-suggested fix in seconds.
Want an AI with memory for your project?
MonsterX AI remembers your codebase across chats.