🔧 Error Fixes

Fix: Python ValueError — too many values to unpack


ValueError: too many values to unpack (expected 2)

This error means you’re trying to unpack a sequence into fewer variables than it contains.

Fix 1: Match the number of variables

# ❌ Broken — 3 values, 2 variables
a, b = [1, 2, 3]

# ✅ Fixed
a, b, c = [1, 2, 3]

Fix 2: Use the star operator to catch extras

# Grab first two, rest goes into a list
first, second, *rest = [1, 2, 3, 4, 5]
# first=1, second=2, rest=[3, 4, 5]

# Grab first and last
first, *middle, last = [1, 2, 3, 4, 5]
# first=1, middle=[2, 3, 4], last=5

Fix 3: Check what you’re actually iterating over

This often happens in loops:

# ❌ If data is a list of 3-element tuples
for key, value in data:  # expects 2, gets 3
    print(key, value)

# ✅ Fixed
for key, value, extra in data:
    print(key, value, extra)

With dictionaries, .items() gives you tuples of 2:

# ❌ Iterating over dict directly gives only keys
for key, value in my_dict:  # Error!
    pass

# ✅ Use .items()
for key, value in my_dict.items():
    print(key, value)

Debugging tip

Print the value before unpacking to see what you’re actually working with:

for item in data:
    print(type(item), len(item), item)
    break  # Just check the first one

See also: Python cheat sheet