Unpacking assigns each item of an iterable to its own name in one statement, and the counts must match exactly. This error means the right side produced more items than the left side has names (its twin, “not enough values to unpack”, is the reverse). The subtlety is that anything iterable can be unpacked, including things you did not mean as sequences: iterating a dictionary yields its keys, and iterating a string yields its characters, so innocent-looking code unpacks surprises.
user = {"name": "Ada", "role": "admin", "active": True}
name, role = user # iterates the dict's *keys*
Traceback (most recent call last):
File "main.py", line 2, in <module>
ValueError: too many values to unpack (expected 2)
# fixed: unpack the values you actually mean
name, role = user["name"], user["role"]
# or, when looping a dict: for key, value in user.items():
.items() or direct key access. Plain iteration over a dict gives keys; unpacking those keys as if they were pairs (or, when keys are strings, unpacking their characters) is the leading cause of this error.first, *_) when trailing values are genuinely unwanted.head, *rest = items absorbs any extra items into a list, and first, *_, last = items keeps only the ends. This is the idiomatic fix when “however many there are” is the honest shape.If the counts in your print look right but the error persists, you are likely unpacking a string you believed was a pair or a row: strings unpack character by character, so a two-name unpack of a 10-character string reports too many values while “looking like” one item in casual prints. Print type() alongside the value.
Why did unpacking my dictionary fail even with the right number of names? Because iterating a dict yields keys, not items: three names against a three-key dict tries to unpack each key in turn or the key sequence itself, not the values. The tool for pairs is dict.items(); for values alone, dict.values().
What does 'expected 2' in the message count? The number of names on the left side of the assignment. The message is precise: it received more items than that count. Comparing it with len() of the right side (printed) shows the exact surplus.