ValueError: too many values to unpack (expected 2)
ValueError: too many values to unpack (expected 2) in Python means the left side of an assignment names fewer variables than the right side produced. Usually a split() with an extra part, or a loop over a dictionary without .items().
How do I fix ValueError: too many values to unpack (expected 2)?
ValueError: too many values to unpack (expected 2) means a, b = ... got more than two items. The usual causes are split() returning extra parts, or looping over a dictionary without .items(). Write for k, v in d.items():, or catch extras with a starred name: first, *rest = parts.
- 1. Print the right sidePrint the value and its len() just before the line. Count the items against the names on the left.
- 2. Dictionary loop needs .items()for name, score in scores unpacks each key string. Write for name, score in scores.items().
- 3. Extra parts or columnsNames, file paths and CSV rows often have more pieces. Use parts[0], parts[-1] or a *rest catch-all.
What does ValueError: too many values to unpack (expected 2) mean?
a, b = something unpacks exactly two items. If something yields three, Python stops rather than guess which one to drop. Python 3.14 adds the actual count when the right side is a list or tuple, for example (expected 2, got 3). The opposite mismatch raises "not enough values to unpack".
Why does ValueError: too many values to unpack (expected 2) happen?
1. Splitting text that has more parts than you assumed
Real names, addresses and file names have more pieces than the example.
Breaks
first, last = "Mary Ann Smith".split()Works
parts = full_name.split()
first, last = parts[0], parts[-1]2. Looping over a dictionary without .items()
A dict gives you its keys, and each key string is then unpacked letter by letter.
Breaks
for name, score in scores:
print(name, score)Works
for name, score in scores.items():
print(name, score)3. A row with an extra column
Data files grow columns; unpacking code does not notice.
Breaks
for name, age in rows: # rows now have 3 columns
...Works
for name, age, *rest in rows:
...How to find it in your own code
Print the right-hand side, and its len(), just before the line. A dictionary needs .items(); a split needs a decision about the extra parts, or a starred catch-all: first, *middle, last = parts.
Try it: fix this bug
easyfirst_and_last("Mary Ann Smith") crashes: ValueError: too many values to unpack (expected 2, got 3).
def first_and_last(full_name):
first, last = full_name.split(" ")
return [first, last]Still not sure why yours breaks?
Paste it into the visualizer and watch it run line by line, with every variable at every step. Free, and it runs in your browser.