ValueError
ValueError: not enough values to unpack (expected 3, got 2)
Traceback
Traceback (most recent call last):
File "main.py", line 1, in <module>
first, second, third = "a,b".split(",")
ValueError: not enough values to unpack (expected 3, got 2)What causes this error
Tuple unpacking expected more values than the iterable contained. The number of variables on the left side exceeds the number of items on the right side.
How to fix it
Use starred unpacking (*rest) for variable-length data. Validate data length before unpacking. Use maxsplit with str.split() to control the number of parts. Add default handling for short data.
Code that causes this error
first, second, third = "a,b".split(",")Fixed code
parts = "a,b".split(",")
first = parts[0] if len(parts) > 0 else ""
second = parts[1] if len(parts) > 1 else ""
third = parts[2] if len(parts) > 2 else ""
# or use starred unpacking:
first, second, *rest = "a,b".split(",")
third = rest[0] if rest else ""About ValueError
This error occurs when tuple unpacking expects more values than the iterable provides. Python's destructuring assignment requires the number of target variables to match the number of values in the iterable (unless you use a starred expression like `*rest`). This commonly happens when processing CSV or delimited data where some rows have fewer fields, when splitting strings that may not contain the expected delimiter, and when iterating over inconsistent data.
The error message helpfully tells you exactly how many values were expected and how many were found. Using the starred unpacking operator (`*rest`) allows capturing remaining values into a list, making the unpacking flexible. The `str.split()` method with a `maxsplit` argument can also help when you need exactly N parts from a string.
Common scenarios
Converting user input strings to numbers without validation
Unpacking iterables with an unexpected number of elements
Passing out-of-range values to mathematical functions
Processing data files with inconsistent or malformed records