Python raises ValueError when a function receives an argument with a correct type but an invalid value. Python valueerror: too many values to unpack (expected 2) means you are trying to access too many values from an iterator.

In this tutorial, we will go through what unpacking is, examples of the error and how to solve it.


Python valueerror: too many values to unpack (expected 2)

Python functions can return more than one variable. We store these returned values in variables and raise the valueerror when there are not enough objects returned to assign to the variables.

What is Unpacking?

Unpacking refers to an operation consisting of assigning an iterable of values to a tuple or a list of variables in a single assignment. The complement to unpacking is packing, which means collecting several values in a single variable. In this context, we can use the unpacking operator * to collect or pack multiple variables in a single variable. In the following example, we will pack a tuple of three values into a single variable using the * operator:

# Pack three values into a single variable 

*x, = 1, 2, 3

print(x)

[1, 2, 3]

The left side of the assignment must be a tuple or a list, which means we need to use a trailing comma. If we do not use a trailing comma, we will raise the SyntaxError: starred assignment target must be in a list or tuple.

Let’s look at the ways of unpacking in Python.

Unpacking using Tuple and List

In Python, we put the tuple of variables on the left side of the assignment operator = and a tuple of values on the right side. The values on the right will be assigned to the variables on the left using their position in the tuple. This operation is generalizable to all kinds of iterables, not just tuples. Unpacking operations are helpful because they make the code more readable.

# Tuple unpacking example

(a, b, c) = (1, 2, 3)

# Print results

print(a)

print(b)

print(c)
1

2

3

To create a tuple object, we do not need to use a pair of parentheses as delimiters. Therefore, the following syntaxes are valid:

# Different syntax for unpacking a tuple and assigning to variables

(a, b, c) = 1, 2, 3

a, b, c = (1, 2, 3)

a, b, c = 1, 2, 3

Let’s look at an example of unpacking a list:

# Unpacking a list and assign to three variables

d, e, f = [4, 5, 6]

print(d)

print(e)

print(f)

4

5

6

If we use two variables on the left and three values on the right, we will raise a ValueError telling us that there are too many values to unpack:

# Trying to assign three values to two variables

a, b = 1, 2, 3
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-15-8904fd2ea925> in <module>
----> 1 a, b = 1, 2, 3

ValueError: too many values to unpack (expected 2)

If we use more variables than values, we will raise a ValueError telling us that there are not enough values to unpack:

# Trying to assign two values to three variables

a, b, c = 1, 2
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-16-9dbc59cfd6c6> in <module>
----> 1 a, b, c = 1, 2

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

Unpacking Using Asterisk

We can use the packing operator * to group variables into a list. Suppose we have a number of variables less than the number of elements in a list. In that case, the packing operator adds the excess elements together as a list and assigns them to the last variable. Let’s look at an example of unpacking using *:

# Using the asterisk to unpack a list with a greater number of values than variables

x, y, *z = [2, 4, 8, 16, 32]

print(x)

print(y)

print(z)

2

4

[8, 16, 32]

We can use the asterisk when we have a function receiving multiple arguments. If we pass a list to a function that needs multiple arguments without unpacking, we will raise a TypeError.

# Define a function which takes three arguments and prints them to the console

def print_func(x, y, z):
    print(x, y, z)

num_list = [2, 4, 6]

print_func(num_list)
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-19-539e296e83e3> in <module>
----> 1 print_func(num_list)

TypeError: print_func() missing 2 required positional arguments: 'y' and 'z'

The function expects three arguments, but num_list is a single argument. To resolve the TypeError, we unpack the list when passing to print_func.

# Define a function which takes three arguments and prints them to the console

def print_func(x, y, z):
    print(x, y, z)

num_list = [2, 4, 6]

# Use the asterisk to unpack the list

print_func(*num_list)
2 4 6 

There are three mistakes that we can make that cause the valueerror: too many values to unpack (expected 2):

  • Trying to iterate over a dictionary and unpack its keys and values separately
  • Not assigning every element in a list to a variable
  • Trying to. unpack too many values while using functions

Example #1: Iterating Over a Dictionary

In Python, a dictionary is a set of unordered items stored as key-value pairs. Let’s consider a dictionary called muon_particle, which holds information about the muon. The dictionary consists of three keys, name, mass, and charge. Each key has a respective value, written to the right side of the key and separated by a colon.

# Example of a dictionary

muon_particle = {
    'name' : 'muon',
    'mass' : 105.66,
    'charge' : -1,
    }
# Iterate over dictionary

for keys, values in muon_particle:

    print(keys, values)

---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-22-5d0b8eff35be> in <module>
----> 1 for keys, values in muon_particle:
      2     print(keys, values)
      3 

ValueError: too many values to unpack (expected 2)

We raise the Value error because each item in the muon_particle dictionary is a value, and keys and values are not distinct values in the dictionary.

Solution

We include the items() method in the for loop to solve this error. This method analyzes a dictionary and returns the keys and values as tuples. Let’s make the change and see what happens.

# Iterate over dictionary using items()

for keys, values in muon_particle.items():

    print(keys, values)
name muon
mass 105.66
charge -1

If we print out the contents of muon_particles.items(), we get the key-value pairs stored as tuples:

print(muon_particle.items())
dict_items([('name', 'muon'), ('mass', 105.66), ('charge', -1)])

Example #2: Unpacking a List to A Variable

If we try to unpack a list to a variable and the number of elements in the list are not equal to the number of assigned variables, we will raise the ValueError. Let’s consider a list of length five, but there are only two variables on the left-hand side of the assignment operator:

# Unpacking a list to variables

x, y = ['we', 'love', 'coding', 'in', 'Python']
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-28-18a4feb7d2d5> in <module>
----> 1 x, y = ['we', 'love', 'coding', 'in', 'Python']

ValueError: too many values to unpack (expected 2)

We have to ensure that the number of variables we want to unpack equals the number of elements in the list.

Solution

We have to make sure there are five variables to unpack the list:

# Unpacking list to variables

x, y, z, a, b = ['we', 'love', 'coding', 'in', 'Python']

print(x)

print(y)

print(z)

print(a)

print(b)

we

love

coding

in

Python

Example #3: Unpacking Too Many Values while using Functions

We can raise the ValueError when calling functions. Let’s look at the input() function, which takes the input from the user, returns a string type value and assigns it to a variable. This example will give the input() function a first and second name as one string. The program will try to assign the input to two variables, first name and last name:

# Using input function to return a string object and assign to two variables

first_name, last_name = input('Enter full name:')
Enter full name:Richard Feynman
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-36-4ae2015f7145> in <module>
----> 1 first_name, last_name = input('Enter full name:')

ValueError: too many values to unpack (expected 2)

We raise the ValueError because the interpreter expects two values, but we return the input as a single string.

Solution

We can use the split() function to solve this error, which returns a list of substrings from a given string. To learn more about getting substrings from strings, go to the article titled “How to Get a Substring From a String in Python”. We create the substring using the delimiter space ' ' chosen by default. Let’s look at the use of split() to solve the error:

# Using input function to return a string object and assign to two variables using split() function

first_name, last_name = input('Enter full name:').split()

print(first_name)

print(last_name)
Richard

Feynman

Summary

Congratulations on reading to the end of this tutorial! The ValueError: too many values to unpack (expected 2)” occurs when you do not unpack all of the items in a list.

A common mistake is trying to unpack too many values into variables. We can solve this by ensuring the number of variables equals the number of items in the list to unpack.

The error can also happen when trying to iterate over the items in a dictionary. To solve this, you need to use the items() method to iterate over a dictionary.

If you are using a function that returns a number of values, ensure you are assigning to an equal number of variables.

If you pass a list to a function, and the function expects more than one argument, you can unpack the list using * when passing the list to the function.

To learn more about Python for data science and machine learning, go to the online courses page on Python for free and easily accessible courses.

Have fun and happy researching!