LinuxPip

“Too many values to unpack” in Python – everything you need to know

Python is famous for its simplicity and beginner-friendly, yet still powerful enough for complex applications like machine learning or super computer programming. It’s the rare tool that can be successfully employed by amateurs and masters alike, powering applications such as Instagram with hundreds of millions of users.

ValueError is one of the most common error messages in Python. The error can be intimidating for beginners, but once you've understood what it means and how to fix it, coding would certainly be easier. In this article, we'll show you details about "Too many values to unpack" - the most popular ValueError message you will encounter. In the end of the post, you would understand the reason behind the error, as well as how to debug your code effectively through our examples.

What "Too many values to unpack" actually means

Python has an unique advantage over other languages : its functions can return multiple variables at once. In other words, you can assign more than one variable with a single function call. To be able to do that, you need to provide the same number of variables to the function call so that Python can "unpack" the returned values to the variables.

If you provide a lower number of variables than what the function returns, "Too many values to unpack" will show up.

Look at the example below to see what I mean :

def gen_numbers():
    return (1,2,3)
one, two = gen_numbers()

Output :

Traceback (most recent call last):
  File "example1.py", line 4, in <module>
    one, two = gen_numbers()
ValueError: too many values to unpack (expected 2)

Simple, right? The gen_number() function returns exactly 3 values, however, we assign them to only 2 variables., that leads to "Too many values to unpack".

The code would be more complex than the example above. In this case, notice that Python has a useful hint in the end of the message that says it expected only 2 values. Cross-check your functions and assignment to see where the problem comes from.

On the opposite side, we have ValueError: not enough values to unpack pops up whenever the number of returned values is lower than the variables that needs to be assigned.

Fix "Too many values to unpack"

Without further details, we cannot give you the solution for your specific problem. But there's a few advices for you to follow.

First, just like the example above, you should ensure your function returns the same number of values as the arguments you're trying to assign.

def gen_numbers():
    return (1,2)            ### Returns 2 values
one, two = gen_numbers()    ### Assign exactly 2 values

If you are iterating through a dictionary, you have to use the dictionary .items() method instead of enumerate() it. This method returns a list of tuples (key, value) so you can assign them both at the same time.

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

If you're slitting a string, or try to split strings from a list, you should be aware of the fact that the results may not have the same length. Look at the example below to see what I mean.

names = [
    'John Oliver',
    'James Thomas Fallon',    # This line produces 2-element list
    'Jimmy Kimmel',
]
for words in names:
    first, last = words.split(" ")  # Cause Too many values to unpack

As you can see, the split() method produces lists with different number of values, which cannot be assigned to 2 variables first and last.

Avoid "Too many values to unpack" in the future

Ensure consistent returns

Now that you knew what caused "Too many values to unpack" error, fixing it should be easy as pie. But in the future, consider writing functions that returns the same amount of data in the same type to avoid getting errors.

For example, one can simply write a function that returns a list of two elements in some case and three elements in others. The function would cause "Too many values to unpack" every time the input argument changes as the number of values returned vary.

def inconsistent(input_value):
    if input_value >= 0:
        return (2,3,4)
    elif ...
        ...
    else:
        return (2,3)

Divide complex one-liner to simple blocks of code

As a Pythonista, you should write simple, concise code instead of using shorthand. All veteran Python developers preach about writing Pythonic code.

Python community is blessed with a relatively simple and complete set of code style guidelines and "Pythonic" idioms. These are one of the key reasons for the readability of Pythonic code. Readability and simplistic syntax is at the heart of Python.

Most of the time, you can break your complex blocks of code into smaller, simpler chunks. That should allow for easier debugging in case any error happens. RealPython's guide for refactoring Python code is a great starting point to follow.

Click to rate this post!
[Total: 1 Average: 5]
Exit mobile version