fix ValueError too many values to unpack error

How to Fix – ValueError too many values to unpack

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

error message "ValueError: too many 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: too many values to unpack the error

This error occurs when you try to unpack more values in fewer 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 fewer variables, you’ll encounter the ValueError: too many values to unpack error.

Let’s look at an example.

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

Output:

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

ValueError                                Traceback (most recent call last)

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

ValueError: too many values to unpack (expected 2)

In the above example, we try to unpack a list with three values in two variables – a and b, since the number of variables is less than the number of values to unpack, we get the error, ValueError: too many values to unpack (expected 2).

You’ll similarly get this error when unpacking more values into fewer variables 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]

    mode = max(set(numbers), key=numbers.count)

    return mean, median, mode

# 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:

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

ValueError                                Traceback (most recent call last)

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

ValueError: too many values to unpack (expected 2)

In the above example, we have a function called calculate_statistics() that returns the mean, median, and mode of a list of numbers. We tried to unpack the return value from the function in just two variables and thus we get the error.

How to fix this error?

To fix the ValueError: too many 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 three values
my_list = [1, 2, 3]
# unpack the list values
a, b, c = my_list

In the above example, we did not get any errors since we are using three variables – a, b, and c to unpack a list with three 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 we do not need that last value from the list and thus there’s no requirement to save it in a variable. In that case, you can –

# 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 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]

    mode = max(set(numbers), key=numbers.count)

    return mean, median, mode

# 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:

Mean: 5.166666666666667
Median: 5.5
Mode: 6

In the above example, we are using the same number of variables (three) 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: too many values to unpack error occurs when you try to unpack more values than the number of variables you have assigned to them. To fix this error, you need to ensure 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