How to Fix Valueerror: too many values to unpack

In this article, I will explain the main reason why you will encounter the Valueerror too many values to unpack error in python and a few different ways to fix it. I think it is essential to understand why this error occurs, just because if you have a good understanding of what caused it, you […]

Card image cap

In this article, I will explain the main reason why you will encounter the Valueerror too many values to unpack error in python and a few different ways to fix it. I think it is essential to understand why this error occurs, just because if you have a good understanding of what caused it, you will avoid this error in the future and write better code.

This tutorial contains some code examples and possible ways to fix the error.

Too many values to unpack

Unpacking is quite a powerful feature in python. Unpacking will assign the values on the right-hand side to the variables on the left-hand side. Each of the values is assigned to one of the variables. Unpacking works when the number of variables and the numbers of values is the same. Every value has a corresponding variable.

See below a simple code snippet that will return the error Valueerror too many values to unpack

name1,name2 = ['Marta','Tristan','Gordon']

Check out the line above. There are three values on the right and only two variables on the left. The name Gordon will be left unassigned. The number of values on the right and the number of variables on the left don’t match. You can fix the code just by removing one of the values. See the code below:

name1,name2 = ['Marta','Tristan']
print(name1)
print(name2)

Output:

Marta
Tristan

For loop example: Too many values to unpack

Another case where the ‘Too many values to unpack’ error may occur when you are looping through dictionary’s entries. See the code snippet below that returns the error:

dict_example = {
    'name': 'John',
    'age':35
}
for key,value in dict_example:
    print(key + " : " + str(value))

Output:

Traceback (most recent call last):
  File  line 5, in <module>
    for key,value in dict_example:
ValueError: too many values to unpack (expected 2)

Why is the code above returning an error? At line 5, the issue is a dictionary used in a loop, by default, will return a list of keys. Unpacking one of the keys, which is one value, into two variables results in an unpacking error.

Solution #1

At the point of unpacking the dictionary entries, the number of values and the number of variables is not matching. One way to solve this is by using the dictionary .items() method. This method returns a list of tuples (key, value), two values for two variables. Problem solved! See the code below:

dict_example = {
    'name': 'John',
    'age':35
}
for key,value in dict_example.items():
    print(key + " : " + str(value))

Output:

name : John
age : 35

Solution #2

I think it is a good idea to see several ways to fix the error, to validate your understanding. Since the problem was having two variables and only one value to assign, another possible solution is to avoid unpacking. How can you do that? Just removing the value variable from the loop. See the code example below:

dict_example = {
    'name': 'John',
    'age':35
}
for key in dict_example: # Removed the value variable
    print(key + " : " + str(dict_example.get(key)))

Output:

name : John
age : 35

This code does the same as solution #1. It is just a different way to solve the same problem. The first solution is slightly more efficient; just you don’t have to search inside the loop.

Split example: Too many values to unpack

The unpacking error could arise when using the .split() method. The code below is the simplest case where using split returns a valueerror.

split1,split2='word1.word2.word3'.split('.')

Why is this code returning an error? The number of values on the right-hand side of the equal sign and the number of variables on the other side are not matching. The result of executing 'word1.word2.word3'.split('.') is a list containing three values: ['word1', 'word2', 'word3'].

Solution #1

The best way to avoid the unpacking error, in this case, is avoiding unpacking. The reason is that if you are not sure what the input of the split will be, you can’t be sure the outcome of splitting will always be two items. Therefore the safest option is avoiding unpacking.

How do you avoid unpacking? Just assigning the result to one variable. See the example below:

list='word1.word2.word3'.split('.')

This code will not raise any error.

Another example

Let’s see another example where you could encounter this unpacking issue. This issue can also arise when using the input() method. See the code example below:

a, b = input("Enter two numbers:")
print(a)
print(b)

The input() method will receive whatever the user type and save it as a string value. Therefore in the code example above, we are trying to assign one value to two variables. That means unpacking error. How can you solve it?

Solution #1

The safest and most straightforward solution is avoiding unpacking by just using one variable.

user_input = input("Enter two numbers:")
split_input=user_input.split()
a = split_input[0]
b = split_input[1]
print(a)
print(b)

Assuming the user enters two numbers separated by white space, this code won’t raise any error.

Solution #2

There is another way to fix the code below; however, this solution is not as safe and predictable as the previous one. Therefore I will encourage you to use the last approach when possible.

Another possible way to fix the code below is calling the .split() method right after receiving the input. That will split the string into a list. However, this approach is not error free. If the user entered more than two numbers, you would end up having the unpacking problem again.

a,b = input("Enter two numbers:")

Solution

a,b = input("Enter two numbers:").split()
print(a)
print(b)

Not enough values to unpack

We have seen the unpacking issue where you have more values than variables. It’s also possible having more variables than values. In that case, you will get a Not enough values to unpack error. The issue is the same, but the other way around, from left to right. See a code example below:

name1,name2,name3,name4 = ['Marta','Tristan','Gordon']

Output:

Traceback (most recent call last):
  File line 4, in <module>
    name1,name2,name3,name4 = ['Marta','Tristan','Gordon']
ValueError: not enough values to unpack (expected 4, got 3)

To prevent this problem, make sure the number of values on one side and the numbers of variables on the other side pair up. In this case, I can avoid the error just by removing the variable name4. See the code below:

name1,name2,name3 = ['Marta','Tristan','Gordon']

Knowledge Quiz Time!

Here is a chance to check how much you learned. See below a few quiz questions that will help you to confirm and reinforce your understanding. Find the solutions at the bottom of this article:

  1. What would this program output?
var1 = 'pear apple'.split(' ')
fruit1, fruit2, fruit3 = ['orange',var1]
print(fruit1)

A) ValueError: not enough values to unpack

B) orange

C) pear

2. What would this program output?

dict = {
    'value1': 1,
    'value2': 2,
    'value3': 3
}
for key, value in dict.items():
    print(value)

A) ValueError: too many values to unpack

B) 1 2 3

C) value1 value2 value3

Conclusion

To summarise, we have seen a few cases where the Valueerror: too many values to unpack error could occur and how you can fix it. You could make sure the values and the variables are pairing up. Another way to avoid this issue is by avoiding unpacking. I hope you enjoy this article, and understand this issue better to avoid it when you are programming.

Thank you so much for reading and supporting this blog!

Happy coding!

Solution

1.A, 2.B

Recommended articles

Learn Ethical Hacking From Scratch Course

Become an ethical hacker that can hack computer systems like black hat hackers and secure them like security experts.

Project-Based Programming Introduction

Steady pace book with lots of worked examples. Starting with the basics, and moving to projects, data visualisation, and web applications

100% Recommended book for Java Beginners

Unique lay-out and teaching programming style helping new concepts stick in your memory

90 Specific Ways to Write Better Python

Great guide for those who want to improve their skills when writing python code. Easy to understand. Many practical examples

Grow Your Java skills as a developer

Perfect Boook for anyone who has an alright knowledge of Java and wants to take it to the next level.

Write Code as a Professional Developer

Excellent read for anyone who already know how to program and want to learn Best Practices

Every Developer should read this

Perfect book for anyone transitioning into the mid/mid-senior developer level

Great preparation for interviews

Great book and probably the best way to practice for interview. Some really good information on how to perform an interview. Code Example in Java