Register Login

ValueError: Too many values to unpack in Python

Updated Mar 31, 2020

Too Many Values to Unpack

Sometimes, you might need to unpack the elements or values from a list. You can assign the extracted values into variables or another new list. But, if the number of list elements is more than the number of variables, an error will be raised during the assignment.  The error ValueError Too many values to unpack in Python will be thrown by Python.

Error Example 1:

exampleList_1 = [3,5,2,6,3]
x,y,z = exampleList_1
print(x)
print(y)
print(z)

Output: 

Traceback (most recent call last):
  File "F:python codeFileName.py", line 2, in <module>
    x,y,z = exampleList_1
ValueError: too many values to unpack (expected 3)

In the above example list, “exampList_1” has five values, and we are trying to unpack these five values with three variables x,y,z.

To solve this problem, kindly check the below example where we are unpacking five values with five variables.

ValueError: Too many values to unpack in Python

Solution:

exampList = [3,5,2,6,4]
x,y,z,a,b = exampList
print(x)
print(y)
print(z)
print(a)
print(b)

Output:

3
5
2
6
4

Error Example 2: Array within an array

exampleList_1 = [[1,2],[3,5],[3,5],[34],3]
x,y,z = exampleList_1
print(x)
print(y)
print(z)

Output

Traceback (most recent call last):
  File "F:python codeFileName.py", line 2, in <module>
    x,y,z = exampleList_1
ValueError: too many values to unpack (expected 3)

Solution

exampleList_1 = [[1,2],[3,5],[3,5],[34],3]
x,y,z,a,b = exampleList_1
print(x)
print(y)
print(z)
print(a)
print(b)

Output:

[1, 2]
[3, 5]
[3, 5]
[34]
3

Conclusion

As mentioned earlier, the best way to avoid the ValueError is by matching the number of variables and the number of list elements. You might also use a for loop to iterate over the elements and print them one by one.


×