Python List ValueError: not enough values to unpack


Python List ValueError: not enough values to unpack

The exception ValueError: not enough values to unpack occurs when you try to unpack the list into more number of variables than the number of items in the list.

In this tutorial, you will learn how to recreate this exception, and how to address this exception, with examples.

For example, consider the following program where we try to unpack our list of five items into seven variables.

Python Program

nums = [100, 200, 300, 400, 500]

num_1, num_2, num_3, num_4, num_5, num_6, num_7 = 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, num_4, num_5, num_6, num_7 = nums
    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: not enough values to unpack (expected 7, got 5)

The exception message not enough values to unpack is clear that there are not enough values in the list to unpack into variables. While the list got 5 items, unpacking is expecting 7 items in the list, because we have given seven variables.

Solution

To rectify this issue, you have to make sure that there are as many number of items in the list as there variables.

Since there are only five values in the given list, we should give only five variables for unpacking the list.

Python Program

nums = [100, 200, 300, 400, 500]

num_1, num_2, num_3, num_4, num_5 = nums

print(f"num_1 is {num_1}")
print(f"num_2 is {num_2}")
print(f"num_3 is {num_3}")
print(f"num_4 is {num_4}")
print(f"num_5 is {num_5}")

Output

num_1 is 100
num_2 is 200
num_3 is 300
num_4 is 400
num_5 is 500

Summary

In this tutorial, we have seen how to handle the exception ValueError: not enough values to unpack when we are unpacking a list.