In this article, we will walk you through the ways to solve the ValueError: Too Many Values to Unpack Error in Python. Let us discuss the possible causes of this error and the corresponding fixes.
ValueError: Too Many Values to Unpack Error in Python
The ValueError: Too Many Values to Unpack Error in Python is often encountered while unpacking an iterable. Say, you have a python list with three items. Now, you want to assign the three items of the list to separate variables.
How many variables would you need? Three of course!
Consider the following example. There is a list called deserts
with 3
items and we assign them to 3
variables, one
, two
, and three
respectively.
You can see the difference in output on printing the entire list and the individual variables.
deserts = ["Vanilla", "Chocolate", "Fudge"]
print(deserts)
one, two, three = deserts
print(one)
print(two)
print(three)
Output
['Vanilla', 'Chocolate', 'Fudge']
Vanilla
Chocolate
Fudge
This is essentially what unpacking means; assignment of values of an iterable to individual variables. It is also referred to as retrieving items from an iterable.
If the number of python variables will be any less than three, then you will get the ValueError: too many values to unpack error. This happens because when the number of variables is not equal to the number of values to be unpacked, Python is confused as to what to assign to which variable and what to leave out.
Let us discuss the various scenarios that might lead to the occurrence of a ValueError: Too Many Values to Unpack Error in Python.
Assignment of Iterable Values to Variables and ValueError in Python
Let us begin with the most basic cause of ValueError: Too Many Values to Unpack Error in Python. As we have already seen previously in an example, to unpack an iterable to variables, the number of variables should be equal to the number of items present in the iterable.
If this is not the case, then we get the ValueError: Too Many Values to Unpack Error in Python. Note that the iterable could be anything starting from a string to a python tuple, a list, a set, or a dictionary.
Consider the following example.
We have a list called length
that has 5
integer values. To unpack this list, we need 5
variables. But as you can see, we only have 4
variables, a
, b
, c
, and d
.
Therefore in the output, we get the ValueError exception. This happens because Python gets confused with what value to assign to which variable since the number of values and variables is unequal.
length = [1, 4, 2, 5, 6]
a, b, c, d = length
print("We get an error")
Output
Traceback (most recent call last):
File "<string>", line 2, in <module>
ValueError: too many values to unpack (expected 4)
To solve this issue, we should put one more variable on the left side.
length = [1, 4, 2, 5, 6]
a, b, c, d, e = length
print("The error is resolved")
Output
The error is resolved
You can also use an underscore(_)
as a placeholder to discard and leave out a value as shown below:
length = [1, 4, 2, 5, 6]
a, b, c, d, _ = length
print("Leave out the last value, 6")
Output
Leave out the last value, 6
ValueError: Too Many Values to Unpack While Iterating Dictionary in Python
A dictionary in Python consists of key-value pairs. Iterating over these pairs is quite confusing at times and may lead to the occurrence of “ValueError: Too Many Values to Unpack” error.
Consider the code given below.
desert = {
"flavor":"Cherry",
"colour":"Red",
"quantity":2
}
for k, v in desert:
print("The attributes: ", k)
print("The values: ", str(v))
Output:
Traceback (most recent call last):
File "<string>", line 6, in <module>
ValueError: too many values to unpack (expected 2)
Here, we first define a dictionary, desert
with 3
key-value pairs. Then, we use a for
loop to iterate over this dictionary and print the key-value pairs. We can also say that we are unpacking the dictionary desert
into two variables: k
and v
.
When you run the code, you will get the “ValueError: Too Many Values to Unpack” error. This happens because we assume the keys and values as separate entities in the dictionary which is not true while we are unpacking a dictionary. In fact, the entire key-value pair of the dictionary is a single item.
To solve this issue, we should use the items()
method. This method treats the key-value pairs as one whole entity and thus the error in unpacking is resolved.
desert = {
"flavor":"Cherry",
"colour":"Red",
"quantity":2
}
for k, v in desert.items():
print("The attribute : ", k)
print("The value : ", str(v))
Output
The attribute : flavor
The value : Cherry
The attribute : colour
The value : Red
The attribute : quantity
The value : 2
You can see that we just added the items()
method on line 6
and this time we get the desired output.
Note that in Python 2.x, in place of the items()
method, we use the iteritems()
method.
Function Return Values and ValueError in Python
We know that when we create a function in Python, we also need to have some variables to store the values that will be returned by the function. Look at this example.
You can see that we have a function price
that calculates the cost of two items. This function returns a single value, which is the total price to be paid.
Now, to receive this value, we must define a variable while calling the function. Here, this variable is total
as you can see in line 5
.
def price(pie, custard):
cost = pie + custard
return cost
total = price(100, 75)
print("Payable amount: ", total)
Output
Payable amount: 175
Now let us change our code a bit. We also want to add some tax to the cost and update the customer about it.
You can see that this time, we return 3
values: cost
, tax
, and total_amount
. To receive these values, we need 3
variables which here are x
, y
, and z
respectively.
def price(pie, custard):
cost = pie + custard
tax = 50
total_amount = cost + tax
return cost, tax, total_amount
x, y, z = price(100, 75)
print("Item total: ", x)
print("Tax added : ", y)
print("Pay this : ", z)
Output
Item total: 175
Tax added : 50
Pay this : 225
But wonder what will happen if the number of values returned is not equal to the number of variables declared to receive them? See this time, we declare only 2
variables.
x, y = price(100, 75)
Output
Traceback (most recent call last):
File "<string>", line 7, in <module>
ValueError: too many values to unpack (expected 2)
You can see that now we get the “ValueError: Too Many Values to Unpack” error because the number of values returned by the function is 3
while the number of variables to receive those values is only 2
.
When you work with functions, it is important to declare as many variables while calling the function as there will be the number of values returned.
However, if you assign a single variable to receive multiple values, it will work fine as it acts as a python tuple.
def price(pie, custard):
cost = pie + custard
tax = 50
total_amount = cost + tax
return cost, tax, total_amount
x = price(100, 75)
print(x)
Output
(175, 50, 225)
The output we get on printing x
is a tuple of all the values returned by the function.
To Sum It Up
In this article, we learned about the “ValueError: Too Many Values to Unpack” Error in Python. We saw the various reasons that cause this error along with the corresponding solutions. We discussed how to avoid getting the “ValueError: Too Many Values to Unpack” Error while unpacking a list, iterating over a dictionary, and returning values from a function.
To learn more about python programming, you can read this article on python simplehttpserver. You might also like this article on try-except vs if else.
This is it for this article. Keep coding!
Donate to Avid Python
Dear reader, If you found this article helpful and informative, I would greatly appreciate your support in keeping this blog running by making a donation. Your contributions help us continue creating valuable content for you and others who come across my blog. No matter how big or small, every donation is a way of saying "thank you" and shows that you value the time and effort we put into writing these articles. If you feel that our article has provided value to you, We would be grateful for any amount you choose to donate. Thank you for your support! Best regards, Aditya Founder
If you want to Pay Using UPI, you can also scan the following QR code.