What this error means

You tried to unpack (assign multiple values at once) but the number of values doesn't match the number of variables. For example, you have 3 values but only 2 variables, or vice versa.

Common causes

  • Unpacking a list/tuple with the wrong number of elements.
  • Function returns more/fewer values than expected.
  • Dictionary items have different structures than expected.

Example that causes the error

data = (1, 2, 3)
a, b = data  # ValueError: 3 values, but only 2 variables

How to fix it: match the count

Make sure the number of variables matches the number of values:

data = (1, 2, 3)
a, b, c = data  # OK: 3 variables for 3 values

Use * to capture extra values

data = (1, 2, 3, 4, 5)
first, second, *rest = data  # OK: rest gets [3, 4, 5]
print(first)   # 1
print(second)  # 2
print(rest)    # [3, 4, 5]

Check length before unpacking

data = (1, 2, 3)
if len(data) == 2:
    a, b = data
else:
    print(f"Expected 2 values, got {len(data)}")

Unpacking dictionary items

person = {'name': 'Alice', 'age': 30, 'city': 'NYC'}
# Each item is a (key, value) tuple:
for key, value in person.items():  # OK: 2 values per item
    print(key, value)