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.
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:
- While unpacking every item from a list, not every item was assigned a variable.
- 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.
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!
ValueError: too many values to unpack
Unpacking refers to retrieving values from a list and assigning them to a list of variables. This error occurs when the number of variables doesn’t match the number of values. As a result of the inequality, Python doesn’t know which values to assign to which variables, causing us to get the error ValueError: too many values to unpack.
Today, we’ll look at some of the most common causes for this ValueError. We’ll also consider the solutions to these problems, looking at how we can avoid any issues.
One of the most frequent causes of this error occurs when unpacking lists.
Let’s say you’ve got a list of kitchen appliances, where you’d like to assign the list values to a couple of variables. We can emulate this process below:
appliances = ['Fridge', 'Microwave', 'Toaster']
appliance_1, appliance_2 = appliances
Out:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-4-2c62c443595d> in <module>
1 appliances = ['Fridge', 'Microwave', 'Toaster']
----> 2 appliance_1, appliance_2 = appliances
ValueError: too many values to unpack (expected 2)
We’re getting this traceback because we’re only assigning the list to two variables when there are three values in the list.
As a result of this, Python doesn’t know if we want Fridge, Microwave or Toaster. We can quickly fix this:
appliances = ['Fridge', 'Microwave', 'Toaster']
appliance_1, appliance_2, appliance_3 = appliances
With the addition of applicance_3, this snippet of code runs successfully since we now have an equal amount of variables and list values.
This change communicates to Python to assign Fridge, Microwave, and Toaster to appliance_1, appliance_2, and appliance_3, respectively.
Let’s say we want to write a function that performs computations on two variables, variable_1 and variable_2, then return the results for use elsewhere in our program.
Specifically, here’s a function that gives us the sum, product and quotient of two variables:
def compute(x, y):
sum = x + y
product = x * y
quotient = x / y
return sum, product, quotient
result_1, result_2 = compute(12, 5)
Out:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-5-9e571b686b4f> in <module>
6 return sum, product, quotient
7
----> 8 result_1, result_2 = compute(12, 5)
ValueError: too many values to unpack (expected 2)
This error is occurs because the function returns three variables, but we are only asking for two.
Python doesn’t know which two variables we’re looking for, so instead of assuming and giving us just two values (which could break our program later if they’re the wrong values), the value error alerts us that we’ve made a mistake.
There are a few options that you can use to capture the function’s output successfully. Some of the most common are shown below.
First we’ll define the function once more:
def compute(x, y):
sum = x + y
product = x * y
quotient = x / y
return sum, product, quotient
Option 1: Assign return values to three variables.
result_1, result_2, result_3 = compute(12, 5)
print(f"Option 1: sum={result_1}, product={result_2}, quotient={result_3}")
Out:
Option 1: sum=17, product=60, quotient=2.4
Now that Python can link the return of sum, product, and quotient directly to result_1, result_2, and result_3, respectively, the program can run without error.
Option 2: Use an underscore to throw away a return value.
result_1, result_2, _ = compute(12, 5)
print(f"Option 2: sum={result_1}, product={result_2}")
Out:
Option 2: sum=17, product=60
The standalone underscore is a special character in Python that allows you to throw away return values you don’t want or need. In this case, we don’t care about the quotient return value, so we throw it away with an underscore.
Option 3: Assign return values to one variable, which then acts like a tuple.
results = compute(12, 5)
print(f"Option 3: sum={results[0]}, product={results[1]}, quotient={results[2]}")
Out:
Option 3: sum=17, product=60, quotient=2.4
With this option, we store all return values in results, which can then be indexed to retrieve each result. If you end up adding more return values later, nothing will break as long as you don’t change the order of the return values.
This ValueError can also occur when reading files. Let’s say we have records of student test results in a text file, and we want to read the data to conduct further analysis. The file test_results.txt looks like this:
80,76,84 83,81,71 89,67,,92 73,80,83
Using the following script, we could create a list for each student, which stores all of their test results after iterating through the lines in the txt file:
with open('test_results.txt', 'r') as f:
file_content = f.read()
file_lines = file_content.split('n') # split file into a list of lines
student_1_scores, student_2_scores, student_3_scores = [], [], []
for line in file_lines:
student_1_score, student_2_score, student_3_score = line.split(',')
student_1_scores.append(student_1_score)
student_2_scores.append(student_2_score)
student_3_scores.append(student_3_score)
Out:
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-14-70781b12ee1c> in <module>
7
8 for line in file_lines:
----> 9 student_1_score, student_2_score, student_3_score = line.split(',')
10 student_1_scores.append(student_1_score)
11 student_2_scores.append(student_2_score)
ValueError: too many values to unpack (expected 3)
If you look back at the text file, you’ll notice that the third line has an extra comma. The line.split(',') code causes Python to create a list with four values instead of the three values Python expects.
One possible solution would be to edit the file and manually remove the extra comma, but this would be tedious to do with a large file containing thousands of rows of data.
Another possible solution could be to add functionality to your script which skips lines with too many commas, as shown below:
with open('test_results.txt', 'r') as f:
file_content = f.read()
file_lines = file_content.split('n')
student_1_scores, student_2_scores, student_3_scores = [], [], []
for index, line in enumerate(file_lines):
try:
student_1_score, student_2_score, student_3_score = line.split(',')
except ValueError:
print(f'ValueError row {index + 1}')
continue
student_1_scores.append(student_1_score)
student_2_scores.append(student_2_score)
student_3_scores.append(student_3_score)
We use try except to catch any ValueError and skip that row. Using continue, we can bypass the rest of the for loop functionality. We’re also printing the problematic rows to alert the user, which allows them to fix the file. In this case, we get the message shown in the output for our code above, alerting the user that line 3 is causing an error.
We get this error when there’s a mismatch between the number of variables to the amount of values Python receives from a function, list, or other collection.
The most straightforward way of avoiding this error is to consider how many values you need to unpack and then have the correct number of available variables. In situations where the number of values to unpack could vary, the best approaches are to capture the values in a single variable (which becomes a tuple) or including features in your program that can catch these situations and react to them appropriately.
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.
Table of contents
- Python valueerror: too many values to unpack (expected 2)
- What is Unpacking?
- Unpacking using Tuple and List
- Unpacking Using Asterisk
- What is Unpacking?
- Example #1: Iterating Over a Dictionary
- Solution
- Example #2: Unpacking a List to A Variable
- Solution
- Example #3: Unpacking Too Many Values while using Functions
- Solution
- Summary
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 refers to 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)])
You can test your Python code using our free online Python compiler.
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.
For further reading on ValueErrors involving unpacking, go to the article: How to Solve Python ValueError: too many values to unpack (expected 3)
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!
In the Python tutorial book I’m using, I typed an example given for simultaneous assignment. I get the aforementioned ValueError when I run the program, and can’t figure out why.
Here’s the code:
#avg2.py
#A simple program to average two exam scores
#Illustrates use of multiple input
def main():
print("This program computes the average of two exam scores.")
score1, score2 = input("Enter two scores separated by a comma: ")
average = (int(score1) + int(score2)) / 2.0
print("The average of the scores is:", average)
main()
Here’s the output.
>>> import avg2
This program computes the average of two exam scores.
Enter two scores separated by a comma: 69, 87
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
import avg2
File "C:Python34avg2.py", line 13, in <module>
main()
File "C:Python34avg2.py", line 8, in main
score1, score2 = input("Enter two scores separated by a comma: ")
ValueError: too many values to unpack (expected 2)
asked Jun 10, 2014 at 21:15
![]()
2
Judging by the prompt message, you forgot to call str.split at the end of the 8th line:
score1, score2 = input("Enter two scores separated by a comma: ").split(",")
# ^^^^^^^^^^^
Doing so splits the input on the comma. See a demonstration below:
>>> input("Enter two scores separated by a comma: ").split(",")
Enter two scores separated by a comma: 10,20
['10', '20']
>>> score1, score2 = input("Enter two scores separated by a comma: ").split(",")
Enter two scores separated by a comma: 10,20
>>> score1
'10'
>>> score2
'20'
>>>
answered Jun 10, 2014 at 21:16
The above code will work fine on Python 2.x. Because input behaves as raw_input followed by a eval on Python 2.x as documented here — https://docs.python.org/2/library/functions.html#input
However, above code throws the error you mentioned on Python 3.x. On Python 3.x you can use the ast module’s literal_eval() method on the user input.
This is what I mean:
import ast
def main():
print("This program computes the average of two exam scores.")
score1, score2 = ast.literal_eval(input("Enter two scores separated by a comma: "))
average = (int(score1) + int(score2)) / 2.0
print("The average of the scores is:", average)
main()
answered Jun 10, 2014 at 21:17
![]()
shaktimaanshaktimaan
11.8k2 gold badges29 silver badges33 bronze badges
1
This is because behavior of input changed in python3
In python2.7 input returns value and your program work fine in this version
But in python3 input returns string
try this and it will work fine!
score1, score2 = eval(input("Enter two scores separated by a comma: "))
answered May 3, 2017 at 6:55
![]()
DexJDexJ
1,25413 silver badges24 bronze badges
that means your function return more value!
ex:
in python2 the function cv2.findContours() return —> contours, hierarchy
but in python3 findContours(image, mode, method[, contours[, hierarchy[, offset]]]) -> image, contours, hierarchy
so when you use those function, contours, hierachy = cv2.findContours(...) is well by python2, but in python3 function return 3 value to 2 variable.
SO ValueError: too many values to unpack (expected 2)
answered Aug 30, 2017 at 2:59
На чтение 5 мин Просмотров 12.7к. Опубликовано 22.11.2021
В этой статье мы рассмотрим из-за чего возникает ошибка ValueError: too many values to unpack и как ее исправить в Python.
Содержание
- Введение
- Что такое распаковка в Python?
- Распаковка списка в Python
- Распаковка списка с использованием подчеркивания
- Распаковка списка с помощью звездочки
- Что значит ValueError: too many values to unpack?
- Сценарий 1: Распаковка элементов списка
- Решение
- Сценарий 2: Распаковка словаря
- Решение
- Заключение
Введение
Если вы получаете ValueError: too many values to unpack (expected 2), это означает, что вы пытаетесь получить доступ к слишком большому количеству значений из итератора.
Ошибка Value Error — это стандартное исключение, которое может возникнуть, если метод получает аргумент с правильным типом данных, но недопустимым значением, или если значение, предоставленное методу, выходит за пределы допустимого диапазона.
В этой статье мы рассмотрим, что означает эта ошибка, в каких случаях она возникает и как ее устранить на примерах.
Что такое распаковка в Python?
В Python функция может возвращать несколько значений, и они могут быть сохранены в переменной. Это одна из уникальных особенностей Python по сравнению с другими языками, такими как C++, Java, C# и др.
Распаковка в Python — это операция, при которой значения итерабильного объекта будут присвоена кортежу или списку переменных.
Распаковка списка в Python
В этом примере мы распаковываем список элементов, где каждый элемент, который мы возвращаем из списка, должен присваиваться переменной в левой части для хранения этих элементов.
one, two, three = [1, 2, 3] print(one) print(two) print(three)
Вывод программы
Распаковка списка с использованием подчеркивания
Подчеркивание чаще всего используется для игнорирования значений; когда _ используется в качестве переменной, когда мы не хотим использовать эту переменную в дальнейшем.
one, two, _ = [1, 2, 3] print(one) print(two) print(_)
Вывод программы
Распаковка списка с помощью звездочки
Недостаток подчеркивания в том, что оно может хранить только одно итерируемое значение, но что если у вас слишком много значений, которые приходят динамически?
Здесь на помощь приходит звездочка. Мы можем использовать переменную со звездочкой впереди для распаковки всех значений, которые не назначены, и она может хранить все эти элементы.
one, two, *z = [1, 2, 3, 4, 5, 6, 7, 8] print(one) print(two) print(z)
Вывод программы
После того, как мы разобрались с распаковкой можно перейти к нашей ошибке.
Что значит ValueError: too many values to unpack?
ValueError: too many values to unpack возникает при несоответствии между возвращаемыми значениями и количеством переменных, объявленных для хранения этих значений. Если у вас больше объектов для присвоения и меньше переменных для хранения, вы получаете ошибку значения.
Ошибка возникает в основном в двух сценариях
Сценарий 1: Распаковка элементов списка
Давайте рассмотрим простой пример, который возвращает итерабильный объект из четырех элементов вместо трех, и у нас есть три переменные для хранения этих элементов в левой части.
В приведенном ниже примере у нас есть 3 переменные one, two, three но мы возвращаем 4 итерабельных элемента из списка.
one, two, three = [1, 2, 3, 4]
Вывод программы
Traceback (most recent call last):
File "/Users/krnlnx/Projects/Test/test.py", line 1, in <module>
one, two, three = [1, 2, 3, 4]
ValueError: too many values to unpack (expected 3)
Решение
При распаковке списка в переменные количество переменных, которые вы хотите распаковать, должно быть равно количеству элементов в списке.
Если вы уже знаете количество элементов в списке, то убедитесь, что у вас есть равное количество переменных в левой части для хранения этих элементов для решения.
Если вы не знаете количество элементов в списке или если ваш список динамический, то вы можете распаковать список с помощью оператора звездочки. Это обеспечит хранение всех нераспакованных элементов в одной переменной с оператором звездочка.
Сценарий 2: Распаковка словаря
В Python словарь — это набор неупорядоченных элементов, содержащих пары ключ-значение. Рассмотрим простой пример, который состоит из трех ключей, и каждый из них содержит значение, как показано ниже.
Если нам нужно извлечь и вывести каждую из пар ключ-значение в словаре, мы можем использовать итерацию элементов словаря с помощью цикла for.
Давайте запустим наш код и посмотрим, что произойдет
city = {"name": "Saint Petersburg", "population": 5000000, "country": "Russia"}
for k, v in city:
print(k, v)
Вывод программы
Traceback (most recent call last):
File "/Users/krnlnx/Projects/Test/test.py", line 3, in <module>
for k, v in city:
ValueError: too many values to unpack (expected 2)
В приведенном выше коде мы получаем ошибку, потому что каждый элемент в словаре «city» является значением.
В Python мы не должны рассматривать ключи и значения в словаре как две отдельные сущности.
Решение
Мы можем устранить ошибку с помощью метода items(). Функция items() возвращает объект представления, который содержит обе пары ключ-значение, сохраненные в виде кортежей.
Подробнее про итерацию словаря читайте по ссылке.
city = {"name": "Saint Petersburg", "population": 5000000, "country": "Russia"}
for k, v in city.items():
print(k, v)
Вывод программы
name Saint Petersburg population 5000000 country Russia
Примечание: Если вы используете Python 2.x, вам нужно использовать функцию iteritems() вместо функции items().
Заключение
В этой статье мы рассмотрели, почему в Python возникает ошибка «ValueError: too many values to unpack », разобрались в причинах и механизме ее возникновения. Мы также увидели, что этой ошибки можно избежать.
Python does not unpack bags well. When you see the error “valueerror: too many values to unpack (expected 2)”, it does not mean that Python is unpacking a suitcase. It means you are trying to access too many values from an iterator.
In this guide, we talk about what this error means and why it is raised. We walk through an example code snippet with this error so you can learn how to solve it.
Find Your Bootcamp Match
- Career Karma matches you with top tech bootcamps
- Access exclusive scholarships and prep courses
Select your interest
First name
Last name
Phone number
By continuing you agree to our Terms of Service and Privacy Policy, and you consent to receive offers and opportunities from Career Karma by telephone, text message, and email.
The Problem: valueerror: too many values to unpack (expected 2)
A ValueError is raised when you try to access information from a value that does not exist. Values can be any object such as a list, a string, or a dictionary.
Let’s take a look at our error message:
valueerror: too many values to unpack (expected 2)
In Python, “unpacking” refers to retrieving items from a value. For instance, retrieving items from a list is referred to as “unpacking” that list. You view its contents and access each item individually.
The error message above tells us that we are trying to unpack too many values from a value.
There are two mistakes that often cause this error:
- When you try to iterate over a dictionary and unpack its keys and values separately.
- When you forget to unpack every item from a list to a variable.
We look at each of these scenarios individually.
Example: Iterating Over a Dictionary
Let’s try to iterate over a dictionary. The dictionary over which we will iterate will store information about an element on the periodic table. First, let’s define our dictionary:
hydrogen = {
"name": "Hydrogen",
"atomic_weight": 1.008,
"atomic_number": 1
}
Our dictionary has three keys and three values. The keys are on the left of the colons; the values are on the right of the colons. We want to print out both the keys and the values to the console. To do this, we use a for loop:
for key, value in hydrogen:
print("Key:", key)
print("Value:", str(value))
In this loop, we unpack “hydrogen” into two values: key and value. We want “key” to correspond to the keys in our dictionary and “value” to correspond to the values.
Let’s run our code and see what happens:
Traceback (most recent call last): File "main.py", line 8, in <module> for key, value in hydrogen: ValueError: too many values to unpack (expected 2)
Our code returns an error.
This is because each item in the “hydrogen” dictionary is a value. Keys and values are not two separate values in the dictionary.
We solve this error by using a method called items(). This method analyzes a dictionary and returns keys and values stored as tuples. Let’s add this method to our code:
for key, value in hydrogen.items():
print("Key:", key)
print("Value:", str(value))
Now, let’s try to run our code again:
Key: name Value: Hydrogen Key: atomic_weight Value: 1.008 Key: atomic_number Value: 1
We have added the items() method to the end of “hydrogen”. This returns our dictionary with key-value pairs stored as tuples. We can see this by printing out the contents of hydrogen.items() to the console:
Our code returns:
dict_items([('name', 'Hydrogen'), ('atomic_weight', 1.008), ('atomic_number', 1)])
Each key and value are stored in their own tuple.
A Note for Python 2.x
In Python 2.x, you use iteritems() in place of items(). This achieves the same result as we accomplished in the earlier example. The items() method is still accessible in Python 2.x.
for key, value in hydrogen.iteritems():
print("Key:", key)
print("Value:", str(value))
Above, we use iteritems() instead of items(). Let’s run our code:
Key: name Value: Hydrogen Key: atomic_weight Value: 1.008 Key: atomic_number Value: 1
Our keys and values are unpacked from the “hydrogen” dictionary. This allows us to print each key and value to the console individually.
Python 2.x is starting to become deprecated. It is best to use more modern methods when available. This means items() is generally preferred over iteritems().
Example: Unpacking Values to a Variable
When you unpack a list to a variable, the number of variables to which you unpack the list items must be equal to the number of items in the list. Otherwise, an error is returned.
We have a list of floating-point numbers that stores the prices of donuts at a local donut store:
donuts = [2.00, 2.50, 2.30, 2.10, 2.20]
We unpack these values into their own variables. Each of these values corresponds to the following donuts sold by the store:
- Raspberry jam
- Double chocolate
- Cream cheese
- Blueberry
We unpack our list into four variables. This allows us to store each price in its own variable. Let’s unpack our list:

«Career Karma entered my life when I needed it most and quickly helped me match with a bootcamp. Two months after graduating, I found my dream job that aligned with my values and goals in life!»
Venus, Software Engineer at Rockbot
raspberry_jam, double_chocolate, cream_cheese, blueberry = [2.00, 2.50, 2.30, 2.10, 2.20] print(blueberry)
This code unpacks our list into four variables. Each variable corresponds with a different donut. We print out the value of “blueberry” to the console to check if our code works. Run our code and see what happens:
Traceback (most recent call last): File "main.py", line 1, in <module> raspberry_jam, double_chocolate, cream_cheese, blueberry = [2.00, 2.50, 2.30, 2.10, 2.20] ValueError: too many values to unpack (expected 4)
We try to unpack four values, our list contains five values. Python does not know which values to assign to our variables because we are only unpacking four values. This results in an error.
The last value in our list is the price of the chocolate donut. We solve our error by specifying another variable to unpack the list:
raspberry_jam, double_chocolate, cream_cheese, blueberry, chocolate = [2.00, 2.50, 2.30, 2.10, 2.20] print(blueberry)
Our code returns: 2.1. Our code successfully unpacks the values in our list.
Conclusion
The “valueerror: too many values to unpack (expected 2)” error occurs when you do not unpack all the items in a list.
This error is often caused by trying to iterate over the items in a dictionary. To solve this problem, use the items() method to iterate over a dictionary.
Another common cause is when you try to unpack too many values into variables without assigning enough variables. You solve this issue by ensuring the number of variables to which a list unpacked is equal to the number of items in the list.
Now you’re ready to solve this Python error like a coding ninja!
Posted by Marta on May 22, 2021 Viewed 48974 times


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:
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:
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:
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:
- 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




Table of Contents
Hide
- What is Unpacking in Python?
- Unpacking using List in Python
- Unpacking list using underscore
- Unpacking list using an asterisk
- What is ValueError: too many values to unpack (expected 2)?
- Scenario 1: Unpacking the list elements
- Error Scenario
- Solution
- Scenario 2: Unpacking dictionary
- Error Scenarios
- Solution
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]
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.
The error “too many values to unpack” is common in Python, you might have seen it while working with lists.
The Python error “too many values to unpack” occurs when you try to extract a number of values from a data structure into variables that don’t match the number of values. For example, if you try to unpack the elements of a list into variables whose number doesn’t match the number of elements in the list.
We will look together at some scenarios in which this error occurs, for example when unpacking lists, dictionaries or when calling Python functions.
By the end of this tutorial you will know how to fix this error if you happen to see it.
Let’s get started!
How Do You Fix the Too Many Values to Unpack Error in Python
What causes the too many values to unpack error?
This happens, for example, when you try to unpack values from a list.
Let’s see a simple example:
>>> week_days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
>>> day1, day2, day3 = week_days
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: too many values to unpack (expected 3)
The error complains about the fact that the values on the right side of the expression are too many to be assigned to the variables day1, day2 and day3.
As you can see from the traceback this is an error of type ValueError.
So, what can we do?
One option could be to use a number of variables on the left that matches the number of values to unpack, in this case seven:
>>> day1, day2, day3, day4, day5, day6, day7 = week_days
>>> day1
'Monday'
>>> day5
'Friday'
This time there’s no error and each variable has one of the values inside the week_days array.
In this example the error was raised because we had too many values to assign to the variables in our expression.
Let’s see what happens if we don’t have enough values to assign to variables:
>>> weekend_days = ['Saturday' , 'Sunday']
>>> day1, day2, day3 = weekend_days
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)
This time we only have two values and we are trying to assign them to the three variables day1, day2 and day3.
That’s why the error says that it’s expecting 3 values but it only got 2.
In this case the correct expression would be:
>>> day1, day2 = weekend_days
Makes sense?
Another Error When Calling a Python Function
The same error can occur when you call a Python function incorrectly.
I will define a simple function that takes a number as input, x, and returns as output two numbers, the square and the cube of x.
>>> def getSquareAndCube(x):
return x**2, x**3
>>> square, cube = getSquareAndCube(2)
>>> square
4
>>> cube
8
What happens if, by mistake, I assign the values returned by the function to three variables instead of two?
>>> square, cube, other = getSquareAndCube(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: not enough values to unpack (expected 3, got 2)
We see the error “not enough values to unpack” because the value to unpack are two but the variables on the left side of the expression are three.
And what if I assign the output of the function to a single variable?
>>> output = getSquareAndCube(2)
>>> output
(4, 8)
Everything works well and Python makes the ouput variable a tuple that contains both values returned by the getSquareAndCube function.
Too Many Values to Unpack With the Input Function
Another common scenario in which this error can occur is when you use the Python input() function to ask users to provide inputs.
The Python input() function reads the input from the user and it converts it into a string before returning it.
Here’s a simple example:
>>> name, surname = input("Enter your name and surname: ")
Enter your name and surname: Claudio Sabato
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
name, surname = input("Enter your name and surname: ")
ValueError: too many values to unpack (expected 2)
Wait a minute, what’s happening here?
Why Python is complaining about too many values to unpack?
That’s because the input() function converts the input into a string, in this case “Claudio Sabato”, and then it tries to assign each character of the string to the variables on the left.
So we have multiple characters on the right part of the expression being assigned to two variables, that’s why Python is saying that it expects two values.
What can we do about it?
We can apply the string method split() to the ouput of the input function:
>>> name, surname = input("Enter your name and surname: ").split()
Enter your name and surname: Claudio Sabato
>>> name
'Claudio'
>>> surname
'Sabato'
The split method converts the string returned by the input function into a list of strings and the two elements of the list get assigned to the variables name and surname.
By default, the split method uses the space as separator. If you want to use a different separator you can pass it as first parameter to the split method.
Using Maxsplit to Solve This Python Error
There is also another way to solve the problem we have observed while unpacking the values of a list.
Let’s start again from the following code:
>>> name, surname = input("Enter your name and surname: ").split()
This time I will provide a different string to the input function:
Enter your name and surname: Mr John Smith
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
name, surname = input("Enter your name and surname: ").split()
ValueError: too many values to unpack (expected 2)
In a similar way as we have seen before, this error occurs because split converts the input string into a list of three elements. And three elements cannot be assigned to two variables.
There’s a way to tell Python to split the string returned by the input function into a number of values that matches the number of variables, in this case two.
Here is the generic syntax for the split method that allows to do that:
<string>.split(separator, maxsplit)
The maxsplit parameter defines the maximum number of splits to be used by the Python split method when converting a string into a list. Maxsplit is an optional parameter.
So, in our case, let’s see what happens if we set maxsplit to 1.
>>> name, surname = input("Enter your name and surname: ").split(' ', 1)
Enter your name and surname: Mr John Smith
>>> name
'Mr'
>>> surname
'John Smith'
The error is gone, the logic of this line is not perfect considering that surname is ‘John Smith’. But this is just an example to show how maxsplit works.
So, why are we setting maxsplit to 1?
Because in this way the string returned by the input function is only split once when being converted into a list, this means the result is a list with two elements (matching the two variables on the left of our expression).
Too Many Values to Unpack with Python Dictionary
In the last example we will use a Python dictionary to explain another common error that shows up while developing.
I have created a simple program to print every key and value in the users dictionary:
users = {
'username' : 'codefather',
'name' : 'Claudio',
}
for key, value in users:
print(key, value)
When I run it I see the following error:
$ python dict_example.py
Traceback (most recent call last):
File "dict_example.py", line 6, in <module>
for key, value in users:
ValueError: too many values to unpack (expected 2)
Where is the problem?
Let’s try to execute a for loop using just one variable:
for user in users:
print(user)
The output is:
$ python dict_example.py
username
name
So…
When we loop through a dictionary using its name we get back just the keys.
That’s why we were seeing an error before, we were trying to unpack each key into two variables: key and value.
To retrieve each key and value from a dictionary we need to use the dictionary items() method.
Let’s run the following:
for user in users.items():
print(user)
This time the output is:
('username', 'codefather')
('name', 'Claudio')
At every iteration of the for loop we get back a tuple that contains a key and its value. This is definitely something we can assign to the two variables we were using before.
So, our program becomes:
users = {
'username' : 'codefather',
'name' : 'Claudio',
}
for key, value in users.items():
print(key, value)
The program prints the following output:
$ python dict_example.py
username codefather
name Claudio
All good, the error is fixed!
Conclusion
We have seen few examples that show when the error “too many values to unpack” occurs and how to fix this Python error.
In one of the examples we have also seen the error “not enough values to unpack”.
Both errors are caused by the fact that we are trying to assign a number of values that don’t match the number of variables we assign them to.
And you? Where are you seeing this error?
Let me know in the comments below 🙂
I have also created a Python program that will help you go through the steps in this tutorial. You can download the source code here.
Related posts:

I’m a Tech Lead, Software Engineer and Programming Coach. I want to help you in your journey to become a Super Developer!