ValuePython Error

ValueError

ValueError: too many values to unpack (expected 2)

Traceback

terminal
Traceback (most recent call last):
  File "main.py", line 1, in <module>
    a, b = (1, 2, 3, 4, 5)
ValueError: too many values to unpack (expected 2)

What causes this error

Tuple unpacking had fewer variables than values in the iterable. The iterable contains more items than the number of target variables.

How to fix it

Use starred unpacking (*rest) to capture excess values. Limit split operations with maxsplit. Check data length before unpacking. Use indexing instead of unpacking for variable-length data.

Code that causes this error

Broken
a, b = (1, 2, 3, 4, 5)

Fixed code

Fixed
a, b, *rest = (1, 2, 3, 4, 5)
# a=1, b=2, rest=[3, 4, 5]

About ValueError

This error is the counterpart of 'not enough values to unpack' — it occurs when the iterable contains more values than there are target variables. This commonly appears when iterating over dictionary `.items()` incorrectly, when splitting strings that contain more delimiters than expected, and when processing data with inconsistent field counts. In Python 3, the starred expression (`*rest`) elegantly handles this by collecting excess values into a list.

Without starred unpacking, you need exactly as many variables as values. This error is especially common when working with data from external sources (APIs, files, user input) where the format may not be perfectly consistent.

Common scenarios

1

Converting user input strings to numbers without validation

2

Unpacking iterables with an unexpected number of elements

3

Passing out-of-range values to mathematical functions

4

Processing data files with inconsistent or malformed records

Related errors