ValueError: too many values to unpack (expected 2)
Python differs from some other languages in that you can pass back multiple values from a function. The number of values that you retrieve from a function needs to match the number of values that you return from the function.
For example, if you have this function:
and then you call the function like this:
that causes this error:
To fix it return three and read three values:
If you liked this story please clap and follow:
Author:
Need Cloud Security Training? 2nd Sight Lab Cloud Security Training
Is your cloud secure? Hire 2nd Sight Lab for a penetration test or security assessment.
Have a Cybersecurity or Cloud Security Question? Ask Teri Radichel by scheduling a call with IANS Research.
[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?
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:
Output is:
2. Unpacking using underscore:
Any unnecessary and unrequired values will be assigned to underscore.
Example:
Output is:
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:
Output is:
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.
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:
To resolve the error, we shall pass my_list by unpacking with an asterisk.
Now, it shall print the output.
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.
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(:),
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.
It will throw a ‘Valueerror: too many values to unpack (expected 2)’ error on running the above code.
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.
Now, it shall now display the below output. It is printing the key and value pair.
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.
The error thrown is given below.
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.
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:
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:
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.
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.
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
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.
"Too many values to unpack" Exception
I’m working on a project in Django and I’ve just started trying to extend the User model in order to make user profiles.
Unfortunately, I’ve run into a problem: Every time I try to get the user’s profile inside of a template ( user.get_template.lastIP , for example), I get the following error:
Any ideas as to what’s going on or what I’m doing wrong?
6 Answers 6
That exception means that you are trying to unpack a tuple, but the tuple has too many values with respect to the number of target variables. For example: this work, and prints 1, then 2, then 3
But this raises your error
Now, the reason why this happens in your case, I don’t know, but maybe this answer will point you in the right direction.
try unpacking in one variable,
python will handle it as a list,
then unpack from the list
![]()
This problem looked familiar so I thought I’d see if I could replicate from the limited amount of information.
A quick search turned up an entry in James Bennett’s blog here which mentions that when working with the UserProfile to extend the User model a common mistake in settings.py can cause Django to throw this error.
To quote the blog entry:
The value of the setting is not "appname.models.modelname", it’s just "appname.modelname". The reason is that Django is not using this to do a direct import; instead, it’s using an internal model-loading function which only wants the name of the app and the name of the model. Trying to do things like "appname.models.modelname" or "projectname.appname.models.modelname" in the AUTH_PROFILE_MODULE setting will cause Django to blow up with the dreaded "too many values to unpack" error, so make sure you’ve put "appname.modelname", and nothing else, in the value of AUTH_PROFILE_MODULE.
If the OP had copied more of the traceback I would expect to see something like the one below which I was able to duplicate by adding "models" to my AUTH_PROFILE_MODULE setting.
This I think is one of the few cases where Django still has a bit of import magic that tends to cause confusion when a small error doesn’t throw the expected exception.
ValueError: too many values to unpack (expected 2)
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.
Cause 1: List Unpacking
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:
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:
Solution
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.
Cause 2: Unpacking Function Returns
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:
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.
Solution
First we’ll define the function once more:
Option 1: Assign return values to three variables.
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.
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.
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.
Cause 3: Dealing with Inconsistencies
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:
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:
Solution
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.
Summary
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.