fix valueerror not enough values to unpack

How to Fix – ValueError not enough values to unpack

In Python, the ValueError: not enough values to unpack occurs if you try to unpack fewer values than the number of variables you have assigned to them. For example, if you’re trying to unpack a list with two values in three variables. This error is commonly encountered when working with lists, tuples, and dictionaries.

ValueError not enough values to unpack

In this tutorial, we will look at the common scenarios in which this error occurs and what you can do to resolve it.

Understanding ValueError: not enough values to unpack the error

This error occurs when you try to unpack fewer values in more variables. Before we dive into the error, let’s see what unpacking is.

What is unpacking in Python?

In Python, unpacking refers to the process of extracting values from an iterable (e.g. list, tuple, dictionary) and assigning them to separate variables in a single statement.

For example, consider the following list:

my_list = [1, 2, 3]

We can unpack the values in my_list and assign them to separate variables like this:

a, b, c = my_list

Now, a will be assigned the value 1, b will be assigned the value 2, and c will be assigned the value 3. Similarly, you can unpack other iterables like tuples and dictionaries.

Unpacking can also be used with functions that return multiple values. For example:

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

def my_function():
    return 1, 2, 3

a, b, c = my_function()

Now, a will be assigned the value 1, b will be assigned the value 2, and c will be assigned the value 3.

Why does this error occur?

When unpacking an iterable, Python expects you to provide the same number of variables as there are values in the iterable you are unpacking. If you use more variables, you’ll encounter the ValueError: not enough values to unpack error.

Let’s look at an example.

# create a list with two values
my_list = [1, 2]
# unpack the list values
a, b, c = my_list

Output:

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

Cell In[1], line 4
      2 my_list = [1, 2]
      3 # unpack the list values
----> 4 a, b, c = my_list

ValueError: not enough values to unpack (expected 3, got 2)

In the above example, we try to unpack a list with two values in three variables – a, b, and c since the number of variables is more than the number of values to unpack, we get the error, ValueError: not enough values to unpack (expected 3, got 2).

You’ll similarly get this error when unpacking less number of values than the variables you’re using to unpack those values in other iterables like tuples, dictionaries, etc.

Another common scenario in which this error occurs is when unpacking the return values from a function. Let’s look at an example.

# function to get descriptive stats of a list of values
def calculate_statistics(numbers):
    """
    This function takes a list of numbers as input and returns the mean, median, and mode.
    """
    mean = sum(numbers) / len(numbers)

    sorted_numbers = sorted(numbers)
    middle_index = len(numbers) // 2

    if len(numbers) % 2 == 0:
        median = (sorted_numbers[middle_index - 1] + sorted_numbers[middle_index]) / 2
    else:
        median = sorted_numbers[middle_index]

    return mean, median

# list of numbers
numbers = [1, 2, 3, 4, 5, 5, 6, 6, 6, 7, 8, 9]
# call the function
mean, median, mode = calculate_statistics(numbers)
print("Mean:", mean)
print("Median:", median)
print("Mode:", mode)

Output:

---------------------------------------------------------------------------

ValueError                                Traceback (most recent call last)

Cell In[2], line 22
     20 numbers = [1, 2, 3, 4, 5, 5, 6, 6, 6, 7, 8, 9]
     21 # call the function
---> 22 mean, median, mode = calculate_statistics(numbers)
     23 print("Mean:", mean)
     24 print("Median:", median)

ValueError: not enough values to unpack (expected 3, got 2)

In the above example, we have a function called calculate_statistics() that returns the mean and the median of a list of numbers. We tried to unpack the return value from the function in three variables (which is more than the number of values being returned from the function) and thus we get the error.

How to fix this error?

To fix the ValueError: not enough values to unpack error, make sure that you are using the same number of variables as there are values in the iterable you are trying to unpack.

Let’s revisit the examples from above and fix them.

# create a list with two values
my_list = [1, 2]
# unpack the list values
a, b = my_list

In the above example, we did not get any errors since we are using two variables – a and b to unpack a list with two values.

Note that if you do not have any use for one or more values from the iterable that you’re unpacking, you can use _ as a placeholder. For example, in the above scenario, let’s say the list has three values and we do not need that last value from the list thus there’s no requirement to save it in a variable. In that case, you can use _ in place of a third variable.

# create a list with three values
my_list = [1, 2, 3]
# unpack the list values
a, b, _ = my_list

We don’t get an error here. Note that you can use _ more than once as well in the same unpacking statement, if you do not want multiple values resulting from unpacking the given iterable.

Let’s now fix the function example.

# function to get descriptive stats of a list of values
def calculate_statistics(numbers):
    """
    This function takes a list of numbers as input and returns the mean, median, and mode.
    """
    mean = sum(numbers) / len(numbers)

    sorted_numbers = sorted(numbers)
    middle_index = len(numbers) // 2

    if len(numbers) % 2 == 0:
        median = (sorted_numbers[middle_index - 1] + sorted_numbers[middle_index]) / 2
    else:
        median = sorted_numbers[middle_index]

    return mean, median

# list of numbers
numbers = [1, 2, 3, 4, 5, 5, 6, 6, 6, 7, 8, 9]
# call the function
mean, median = calculate_statistics(numbers)
print("Mean:", mean)
print("Median:", median)

Output:

Mean: 5.166666666666667
Median: 5.5

In the above example, we are using the same number of variables (two) as the number of values being returned from the calculate_statistics() function. You can see that we did not get an error here.

Conclusion

The ValueError: not enough values to unpack error occurs when you try to unpack fewer values than the number of variables you have assigned to them. To fix this error, you need to make sure the number of variables you have assigned to the values you are trying to unpack is equal to the number of values you are trying to unpack.

Author

  • Piyush Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top