ValueError: too many values to unpack

During a multiple value assignment, the ValueError: too many values to unpack occurs when either you have more objects to assign than variables or you don’t have enough variables to assign objects.

Python has a unique feature that python can store multiple values for variables in the assignment operator. The ValueError: too many values to unpack caused by the mismatch between the number of values returned and the number of variables in the assignment statement.

The value error “too many values to unpack” is due to the mismatch and is similar to the one below.

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 1, in <module>
    a, b, c = "Lion", "Tiger", "Monkey", "Giraffe"
ValueError: too many values to unpack (expected 2)


Root Cause

The value error is due to either you have more values than the variables available or not having enough variables for the Objects. The mismatch between the number of variables and the number of values causes this error.



Solution 1

Find the number of values returned by the program in python. Check the number of variables you want to assign to these values. If the number of variables is less than the values, add additional variables to the assignment operator. The new variables will be assigned with additional values.

Example

a, b, c = "Lion", "Tiger", "Monkey", "Giraffe"

print(a)
print(b)
print(c)

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 1, in <module>
    a, b, c = "Lion", "Tiger", "Monkey", "Giraffe"
ValueError: too many values to unpack
[Finished in 0.0s with exit code 1]

Solution

a, b, c, d = "Lion", "Tiger", "Monkey", "Giraffe"

print(a)
print(b)
print(c)
print(d)

Output

Lion
Tiger
Monkey
Giraffe
[Finished in 0.1s]


Solution 2

Find the number of variables in the assignment. Check the number of returned values. If the number of values returned is more than the variables available, filter the number of values to the variables count. When assigning variables, the excess value is ignored.

Example

a, b, c = "Lion", "Tiger", "Monkey", "Giraffe"

print(a)
print(b)
print(c)

Output

Traceback (most recent call last):
  File "/Users/python/Desktop/test.py", line 1, in <module>
    a, b, c = "Lion", "Tiger", "Monkey", "Giraffe"
ValueError: too many values to unpack
[Finished in 0.0s with exit code 1]

Solution

a, b, c = "Lion", "Tiger", "Monkey"

print(a)
print(b)
print(c)

Output

Lion
Tiger
Monkey
[Finished in 0.0s]



Related Articles

Leave a Reply

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