ValueError: too many values to unpack (expected 2) in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
4 min

banner

# ValueError: too many values to unpack (expected 2) in Python

The Python "ValueError: too many values to unpack (expected 2) in Python" occurs when the number of variables in the assignment is not the same as the number of values in the iterable.

To solve the error, declare exactly as many variables as there are items in the iterable.

valueerror too many values to unpack expected 2

Here is an example of how the error occurs.

main.py
# โ›”๏ธ ValueError: too many values to unpack (expected 2) a, b = ['apple', 'banana', 'kiwi']
We declare 2 variables, but the list contains 3 items. The inconsistency between the number of variables and items in the list causes the error.

# Declare exactly as many variables as there are items in the iterable

To solve the error, make sure to declare exactly as many variables as there are items in the iterable.

main.py
a, b, k = ['apple', 'banana', 'kiwi'] print(a) # ๐Ÿ‘‰๏ธ 'apple' print(b) # ๐Ÿ‘‰๏ธ 'banana' print(k) # ๐Ÿ‘‰๏ธ 'kiwi'

declare correct number of variables

We declared 3 variables and the list contains 3 values, so everything works as expected.

Similarly, if the list has 2 items, declare 2 variables.

main.py
a, b = ['apple', 'banana'] print(a) # ๐Ÿ‘‰๏ธ 'apple' print(b) # ๐Ÿ‘‰๏ธ 'banana'

If you don't need to use one or more of the values, use an underscore as a placeholder.

main.py
a, b, _ = ['one', 'two', 'three'] print(a) # ๐Ÿ‘‰๏ธ one print(b) # ๐Ÿ‘‰๏ธ two

use underscore for placeholder variables

The underscore has no special meaning. It is used as a throwaway variable and signals to the reader of your code that the value isn't needed.

You can use as many underscores as necessary when unpacking.

main.py
a, _, c, _ = ['one', 'two', 'three', 'four'] print(a) # ๐Ÿ‘‰๏ธ one print(c) # ๐Ÿ‘‰๏ธ three

# Use the items() method to iterate over a dictionary

The error is often caused when trying to iterate over a dictionary without using the items() method.

main.py
my_dict = {'name': 'Bobby Hadz', 'age': 29} # โ›”๏ธ ValueError: too many values to unpack (expected 2) for key, value in my_dict: print(key, value)

When we use a for loop to iterate over a dictionary, we only get access to the key.

main.py
my_dict = {'name': 'Bobby Hadz', 'age': 29} for key in my_dict: # name Bobby Hadz # age 29 print(key, my_dict[key])

We can use the dict.items() method to iterate over a dictionary with access to the keys and values.

main.py
my_dict = {'name': 'Bobby Hadz', 'age': 29} for key, value in my_dict.items(): print(key, value) # ๐Ÿ‘‰๏ธ name Bobby Hadz, age 29

use items when iterating over dictionary

The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).

main.py
my_dict = {'name': 'Bobby Hadz', 'age': 29} # ๐Ÿ‘‡๏ธ dict_items([('name', 'Bobby Hadz'), ('age', 29)]) print(my_dict.items())

The first element in each tuple is the key and the second is the value.

# Iterating over a list or tuple with access to the index

You might also get the error when trying to iterate over a list or a tuple with the index.

main.py
my_list = ['apple', 'banana', 'melon'] # โ›”๏ธ ValueError: too many values to unpack (expected 2) for index, item in my_list: print(index, item)

When iterating over a list with a for loop, we only get access to the item of the current iteration.

You can use the enumerate function to iterate over a list or tuple with the index.

main.py
my_list = ['apple', 'banana', 'melon'] for index, item in enumerate(my_list): print(index, item) # ๐Ÿ‘‰๏ธ 0 apple, 1 banana, 2 melon

iterating over list with index

The enumerate function takes an iterable and returns an enumerate object containing tuples where the first element is the index and the second is the item.

# Unpacking the items of a function's return value

The error also occurs when we try to unpack the items of a function's return value.

main.py
def get_tuple(): return ('apple', 'banana', 'kiwi') # โ›”๏ธ ValueError: too many values to unpack (expected 2) a, b = get_tuple()

The tuple contains 3 elements, but we only declared 2 variables.

Make sure to declare exactly as many variables as there are items in the iterable that the function returns.

main.py
def get_tuple(): return ('apple', 'banana', 'kiwi') a, b, k = get_tuple() print(a) # ๐Ÿ‘‰๏ธ 'apple' print(b) # ๐Ÿ‘‰๏ธ 'banana' print(k) # ๐Ÿ‘‰๏ธ 'kiwi'

unpacking tuple correctly

The function returns a tuple containing 3 elements, so we have to declare exactly 3 variables.

# Unpacking values from a string

The error is also caused when we try to unpack values from a string.

main.py
my_str = 'apple,banana' # โ›”๏ธ ValueError: too many values to unpack (expected 2) a, b = my_str

When unpacking from a string, each variable declaration counts for a single character.

main.py
a, b, c = 'xyz' print(a) # ๐Ÿ‘‰๏ธ x print(b) # ๐Ÿ‘‰๏ธ y print(c) # ๐Ÿ‘‰๏ธ z

unpacking characters from string

To solve the error, we have to split the string on the comma before unpacking the values.

main.py
my_list = 'apple,banana'.split(',') print(my_list) # ๐Ÿ‘‰๏ธ ['apple', 'banana'] a, b = my_list print(a) # ๐Ÿ‘‰๏ธ 'apple' print(b) # ๐Ÿ‘‰๏ธ 'banana'

split before unpacking

The str.split() method splits the string into a list of substrings using a delimiter.

The method takes the following 2 parameters:

NameDescription
separatorSplit the string into substrings on each occurrence of the separator
maxsplitAt most maxsplit splits are done (optional)
When no separator is passed to the str.split() method, it splits the input string on one or more whitespace characters.
main.py
print('bobby,hadz'.split(',')) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz'] print('bobby_hadz'.split('_')) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz'] print('bobby hadz'.split(' ')) # ๐Ÿ‘‰๏ธ ['bobby', 'hadz']

If you meant to unpack specific characters into variables, make sure to declare exactly as many variables as there are characters in the string.

main.py
my_str = 'hi' h, i = my_str print(h) # ๐Ÿ‘‰๏ธ 'h' print(i) # ๐Ÿ‘‰๏ธ 'i'

I've also written an article on how to access multiple elements in a list by their indices.

Want to learn more about accessing values in Python sequences? Check out these resources: Get multiple values from a Dictionary in Python,Using multiple variables in a For loop in Python.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev