[Solved] Valueerror: Too Many Values to Unpack (Expected 2)

Errors are illegal operations or mistakes. As a result, a program behaves unexpectedly. In python, there are three types of errors – Syntax errors, logic errors, and exceptions. Valuerror is one such error. Python raises valueerror when a function receives an argument that has a correct type but an invalid value. ‘Python valueerror: too many values to unpack (expected 2)’ occurs when you are trying to access too many values from an iterator than expected.

Introduction to Valueerror: too many values to unpack (expected 2)

Functions in python have the ability to return multiple variables. These multiple values returned by functions can be stored in other variables. ‘Python valueerror: too many values to unpack (expected 2)’ occurs when more objects have to be assigned variables than the number of variables or there aren’t enough objects present to assign to the variables.

What is Unpacking?

Unpacking in python refers to the operation where an iterable of values must be assigned to a tuple or list of variables. The three ways for unpacking are:

1. Unpacking using tuple and list:

When we write multiple variables on the left-hand side of the assignment operator separated by commas and tuple or list on the right-hand side, each tuple/list value will be assigned to the variables left-hand side.

Example:

x,y,z = [10,20,30]
print(x)
print(y)
print(z)

Output is:

10
20
30

2. Unpacking using underscore:

Any unnecessary and unrequired values will be assigned to underscore.

Example:

x,y,_ = [10,20,30]
print(x)
print(y)
print(_)

Output is:

10
20
30

3. Unpacking using asterisk(*):

When the number of variables is less than the number of elements, we add the elements together as a list to the variable with an asterisk.

Example:

x,y,*z = [10,20,30,40,50]
print(x)
print(y)
print(z)

Output is:

10
20
[30, 40, 50]

We unpack using an asterisk in the case when we have a function receiving multiple arguments. And we want to call this function by passing a list containing the argument values.

def my_func(x,y,z):
    print(x,y,z)
 
my_list = [10,20,30]
 
my_func(my_list)#This throws error

The above code shall throw an error because it will consider the list ‘my_list’ as a single argument. Thus, the error thrown will be:

      4 my_list = [10,20,30]
      5 
----> 6 my_func(my_list)#This throws error

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

To resolve the error, we shall pass my_list by unpacking with an asterisk.

def my_func(x,y,z):
    print(x,y,z)
 
my_list = [10,20,30]
 
my_func(*my_list)

Now, it shall print the output.

10 20 30

What exactly do we mean by Valueerror: too many values to unpack (expected 2)?

The error message indicates that too many values are being unpacked from a value. The above error message is displayed in either of the below two cases:

  1. While unpacking every item from a list, not every item was assigned a variable.
  2. While iterating over a dictionary, its keys and values are unpacked separately.

Also, Read | [Solved] ValueError: Setting an Array Element With A Sequence Easily

Valueerror: too many values to unpack (expected 2) while working with dictionaries

In python, a dictionary is a set of unordered items. Each dictionary is stored as a key-value pair. Lets us consider a dictionary here named college_data. It consists of three keys: name, age, and grade. Each key has a respective value stored against it. The values are written on the right-hand side of the colon(:),

college_data = {
      'name' : "Harry",
      'age' : 21,
      'grade' : 'A',
}

Now, to print keys and values separately, we shall try the below code snippet. Here we are trying to iterate over the dictionary values using a for loop. We want to print each key-value pair separately. Let us try to run the below code snippet.

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

It will throw a ‘Valueerror: too many values to unpack (expected 2)’ error on running the above code.

----> 1 for keys, values in college_data:
      2   print(keys)
      3   print(values)

ValueError: too many values to unpack (expected 2)

This happens because it does not consider keys and values are separate entities in our ‘college_data’ dictionary.

For solving this error, we use the items() function. What do items() function do? It simply returns a view object. The view object contains the key-value pairs of the college_data dictionary as tuples in a list.

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

Now, it shall now display the below output. It is printing the key and value pair.

name Harry
age 21
grade A

Valueerror: too many values to unpack (expected 2) while unpacking a list to a variable

Another example where ‘Valueerror: too many values to unpack (expected 2)’ is given below.

Example: Lets us consider a list of length four. But, there are only two variables on the left hand of the assignment operator. So, it is likely that it would show an error.

var1,var2=['Learning', 'Python', 'is', 'fun!']

The error thrown is given below.

ValueError                            Traceback (most recent call last)
<ipython-input-9-cd6a92ddaaed> in <module>()
----> 1 var1,var2=['Learning', 'Python', 'is', 'fun!']

ValueError: too many values to unpack (expected 2)

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

The problem can be avoided by checking the number of elements in the list and have the exact number of variables on the left-hand side. You can also unpack using an asterisk(*). Doing so will store multiple values in a single variable in the form of a list.

var1,var2, *temp=['Learning', 'Python', 'is', 'fun!']

In the above code, var1 and var2 are variables, and the temp variable is where we shall be unpacking using an asterisk. This will assign the first two strings to var1 and var2, respectively, and the rest of the elements would be stored in the temp variable as a list.

print(var1, var2, temp)

The output is:

Learning Python ['is', 'fun!']

Valueerror: too many values to unpack (expected 2) while using functions

Another example where Valueerror: too many values to unpack (expected 2) is thrown is calling functions.

Let us consider the python input() function. Input() function reads the input given by the user, converts it into a string, and assigns the value to the given variable.

Suppose if we want to input the full name of a user. The full name shall consist of first name and last name. The code for that would be:

fname, lname = input('Enter Name:')

It would list it as a valueerror because it expects two values, but whatever you would give as input, it would consider it a single string.

Enter Name:Harry Potter
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-7-4d08b7961d29> in <module>()
----> 1 fname, lname = input('Enter Name:')

ValueError: too many values to unpack (expected 2)

So, to solve the valuerror, we can use the split() function here. The split() method in python is returning a list of substrings from a given string. The substring is created based on the delimiter mentioned: a space(‘ ‘) by default. So, here, we have to split a string containing two subparts.

fname, lname = input('Enter Name:').split()

Now, it will not throw an error.

Summarizing the solutions:

  • Match the numbers of variables with the list elements
  • Use a loop to iterate over the elements one at a time
  • While separating key and value pairs in a dictionary, use items()
  • Store multiple values while splitting into a list instead or separate variables

FAQ’s

Q. Difference between TypeError and ValueError.

A. TypeError occurs when the type of the value passed is different from what was expecting. E.g., When a function was expecting an integer argument, but a list was passed. Whereas, ValueError occurs when the value mentioned is different than what was expected. E.g., While unpacking a list, the number of variables is less than the length of the list.

Q. What is valueerror: too many values to unpack (expected 2) for a tuple?

A. The above valuerror occurs while working with a tuple for the same reasons while working with a list. When the number of elements in the tuple is less than or greater than the number of variables for unpacking, the above error occurs.

Happy Learning!

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments