ValueError: not enough values to unpack (expected 3, got 2)

Loading

The error message:

ValueError: not enough values to unpack (expected 3, got 2)

occurs when you try to unpack fewer values than expected from a tuple, list, or iterable.


1. Causes and Solutions

Cause 1: Mismatched Number of Variables and Values in Tuple Unpacking

Python allows unpacking values from a tuple or list into separate variables. However, if the number of variables does not match the number of values, this error occurs.

Incorrect Code:

a, b, c = (1, 2)  # Expecting 3 values but only 2 provided

Solution: Ensure the number of variables matches the number of values.

a, b = (1, 2)  # Correct
print(a, b) # Output: 1 2

or use * to capture extra or missing values:

a, b, *rest = (1, 2)  # Handles missing third value
print(a, b, rest) # Output: 1 2 []

Cause 2: Unpacking More Values Than Provided in a Loop

When iterating over a sequence of tuples (e.g., a list of tuples), unpacking must match the structure.

Incorrect Code:

data = [(1, 2), (3, 4, 5)]
for x, y, z in data: # The first tuple has only 2 values
print(x, y, z) # Error on (1,2)

Solution: Use * to handle extra/missing values.

for x, y, *z in data:
print(x, y, z) # Output: 1 2 [] and 3 4 [5]

Cause 3: Unpacking Strings Incorrectly

A string is an iterable, so unpacking it must match the length.

Incorrect Code:

a, b, c = "Hi"  # Only 2 characters, expecting 3

Solution: Use * to capture extra/missing values.

a, b, *c = "Hi"
print(a, b, c) # Output: H i []

or ensure the string has enough characters:

a, b, c = "Hey"  # Works fine

Cause 4: Using zip() with Mismatched List Lengths

If you unpack values from zip(), but one list is shorter, this error may occur.

Incorrect Code:

pairs = list(zip([1, 2], ["a", "b", "c"]))  # Only 2 pairs are created
for x, y, z in pairs: # Expecting 3 values, but each tuple has 2
print(x, y, z)

Solution: Ensure lists have the same length or use *rest:

pairs = list(zip([1, 2, 3], ["a", "b", "c"]))  # Now tuples have 3 elements
for x, y, z in pairs:
print(x, y, z)

Leave a Reply

Your email address will not be published. Required fields are marked *