Online Tutorials & Training Materials | STechies.com
Register Login

ValueError: Too many values to unpack in Python

|| 0

ValueError: Too many values to unpack in Python
Stechies

Too many values to unpack

This error occurs when you assign more number of values than the number of variables, for example you have a list and the length of this list is five elements.

In the following example we are trying to unpack this list which has length of 5 elements with 3 variables, As output it will give an error “Too many values to unpack”.

Example:

exampList  =  [3,5,2,6,3]
x,y,z =  exampList 
print x
print y
print z

Output: 

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

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

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

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

Example of  array within array

exampList  =  [[1,2],[3,5],[3,5],[34],3]
x,y,z,a,b=  exampList
print x
print y
print z
print a
print b

Output:

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