ValueError: too many values to unpack (expected 2)

If you get ValueError: too many values to unpack (expected 2), it means that you are trying to access too many values from an iterator. Value Error is a standard exception that can occur if the method receives an argument with the correct data type but an invalid value or if the value provided to the method falls outside the valid range.

In this article, let us look at what this error means and the scenarios you get this error, and how to resolve the error with examples.

What is Unpacking in Python?

In Python, the function can return multiple values, and it can be stored in the variable. This is one of the unique features of Python when compared to other languages such as C++, Java, C#, etc. 

Unpacking in Python is an operation where an iterable of values will be assigned to a tuple or list of variables.

Unpacking using List in Python

In this example, we are unpacking the list of elements where each element that we return from the list should assign to a variable on the left-hand side to store these elements.

x,y,z = [5,10,15]
print(x)
print(y)
print(z)

Output

5
10
15

Unpacking list using underscore

Underscoring is most commonly used to ignore values; when underscore "_" is used as a variable it means that we do not want to use that variable and its value at a later point.

x,y,_ = [5,10,15]
print(x)
print(y)
print(_)

Output

5
10
15

Unpacking list using an asterisk

The drawback with an underscore is it can just hold one iterable value, but what if you have too many values that come dynamically? Asterisk comes as a rescue over here. We can use the variable with an asterisk in front to unpack all the values that are not assigned, and it can hold all these elements in it.

x,y, *z = [5,10,15,20,25,30]
print(x)
print(y)
print(z)

Output

5
10
[15, 20, 25, 30]

What is ValueError: too many values to unpack (expected 2)?

ValueError: too many values to unpack (expected 2) occurs when there is a mismatch between the returned values and the number of variables declared to store these values. If you have more objects to assign and fewer variables to hold, you get a value error.

The error occurs mainly in 2 scenarios-

Scenario 1: Unpacking the list elements

Let’s take a simple example that returns an iterable of three items instead of two, and we have two variables to hold these items on the left-hand side, and Python will throw ValueError: too many values to unpack.

In the below example we have 2 variables x and y but we are returning 3 iterables elements from the list.

Error Scenario

x,y =[5,10,15]

Output

Traceback (most recent call last):
  File "c:/Projects/Tryouts/main.py", line 1, in <module>
    x,y =[5,10,15]
ValueError: too many values to unpack (expected 2)

Solution

While unpacking a list into variables, the number of variables you want to unpack must equal the number of items in the list. 

If you already know the number of elements in the list, then ensure you have an equal number of variables on the left-hand side to hold these elements to solve.

If you do not know the number of elements in the list or if your list is dynamic, then you can unpack the list with an asterisk operator. It will ensure that all the un-assigned elements will be stored in a single variable with an asterisk operator.

# In case we know the number of elements
# in the list to unpack
x,y,z =[5,10,15]
print("If we know the number of elements in list")
print(x)
print(y)
print(z)

# if the list is dynamic
a,b, *c = [5,10,15,20,25,30]
print("In case of dynamic list")
print(a)
print(b)
print(c)

Output

If we know the number of elements in list
5
10
15
In case of dynamic list
5
10
[15, 20, 25, 30]

Scenario 2: Unpacking dictionary 

In Python, Dictionary is a set of unordered items which holds key-value pairs. Let us consider a simple example of an employee, which consists of three keys, and each holds a value, as shown below.

If we need to extract and print each of the key and value pairs in the employee dictionary, we can use iterate the dictionary elements using a for loop. 

Let’s run our code and see what happens

Error Scenarios

# Unpacking using dictornary

employee= {
    "name":"Chandler",
    "age":25,
    "Salary":10000
}

for keys, values in employee:
  print(keys,values)

Output

Traceback (most recent call last):
  File "c:/Projects/Tryouts/main.py", line 9, in <module>
    for keys, values in employee:
ValueError: too many values to unpack (expected 2)

We get a Value error in the above code because each item in the “employee” dictionary is a value. We should not consider the keys and values in the dictionary as two separate entities in Python.

Solution

We can resolve the error by using a method called items(). The items() function returns a view object which contains both key-value pairs stored as tuples.

# Unpacking using dictornary

employee= {
    "name":"Chandler",
    "age":25,
    "Salary":10000
}

for keys, values in employee.items():
  print(keys,values)

Output

name Chandler
age 25
Salary 10000

Note: If you are using Python version 2.x, you need to use iteritems() instead of the items() function. 

2 comments
  1. I think it should be a, b, c to print in the dynamic example.

    # In case we know the number of elements
    # in the list to unpack
    x,y,z =[5,10,15]
    print(“If we know the number of elements in list”)
    print(x)
    print(y)
    print(z)

    # if the list is dynamic
    a,b, *c = [5,10,15,20,25,30]
    print(“In case of dynamic list”)
    print(x)
    print(y)
    print(z)

Leave a Reply

Your email address will not be published. Required fields are marked *

Sign Up for Our Newsletters

Subscribe to get notified of the latest articles. We will never spam you. Be a part of our ever-growing community.

You May Also Like