Python List ValueError: too many values to unpack
Python List ValueError: too many values to unpack
The exception ValueError: too many values to unpack occurs when you try to unpack a list with number of values in the list greater than the number of variables provided to unpack.
In this tutorial, you will learn how to recreate this exception, and how to address this exception, with examples.
For example, in the following program, we tried unpacking a list of five items into three variables.
Python Program
nums = [100, 200, 300, 400, 500]
num_1, num_2, num_3 = nums
print(f"num_1 is {num_1}")
print(f"num_2 is {num_2}")
print(f"num_3 is {num_3}")
Output
Traceback (most recent call last):
File "/Users/pythonexamplesorg/main.py", line 3, in <module>
num_1, num_2, num_3 = nums
^^^^^^^^^^^^^^^^^^^
ValueError: too many values to unpack (expected 3)
We get ValueError exception. And the message too many values to unpack is clear, that there are too many values in the list to unpack into the expected 3 variables.
Solution
If we are interested in unpacking only the first three items in the list to three variables, you have to first unpack the starting required number of items into variables, and then assign the rest into a new list using asterisk symbol as shown in the following statement.
num_1, num_2, num_3, *others = nums
Let us use this statement to unpack the list into fewer number of variables, and run the program.
Python Program
nums = [100, 200, 300, 400, 500]
num_1, num_2, num_3, *others = nums
print(f"num_1 is {num_1}")
print(f"num_2 is {num_2}")
print(f"num_3 is {num_3}")
Output
num_1 is 100
num_2 is 200
num_3 is 300
Summary
In this tutorial, we have seen how to handle the exception ValueError: too many values to unpack when we are unpacking a list.