Last updated: Apr 8, 2024
Reading timeยท4 min
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.
Here is an example of how the error occurs.
# โ๏ธ ValueError: too many values to unpack (expected 2) a, b = ['apple', 'banana', 'kiwi']
To solve the error, make sure to declare exactly as many variables as there are items in the iterable.
a, b, k = ['apple', 'banana', 'kiwi'] print(a) # ๐๏ธ 'apple' print(b) # ๐๏ธ 'banana' print(k) # ๐๏ธ 'kiwi'
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.
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.
a, b, _ = ['one', 'two', 'three'] print(a) # ๐๏ธ one print(b) # ๐๏ธ two
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.
a, _, c, _ = ['one', 'two', 'three', 'four'] print(a) # ๐๏ธ one print(c) # ๐๏ธ three
items()
method to iterate over a dictionaryThe error is often caused when trying to iterate over a dictionary without using
the items()
method.
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.
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.
my_dict = {'name': 'Bobby Hadz', 'age': 29} for key, value in my_dict.items(): print(key, value) # ๐๏ธ name Bobby Hadz, age 29
The dict.items() method returns a new view of the dictionary's items ((key, value) pairs).
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.
You might also get the error when trying to iterate over a list or a tuple with the index.
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.
my_list = ['apple', 'banana', 'melon'] for index, item in enumerate(my_list): print(index, item) # ๐๏ธ 0 apple, 1 banana, 2 melon
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.
The error also occurs when we try to unpack the items of a function's return value.
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.
def get_tuple(): return ('apple', 'banana', 'kiwi') a, b, k = get_tuple() print(a) # ๐๏ธ 'apple' print(b) # ๐๏ธ 'banana' print(k) # ๐๏ธ 'kiwi'
The function returns a tuple containing 3 elements, so we have to declare exactly 3 variables.
The error is also caused when we try to unpack values from a string.
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.
a, b, c = 'xyz' print(a) # ๐๏ธ x print(b) # ๐๏ธ y print(c) # ๐๏ธ z
To solve the error, we have to split the string on the comma before unpacking the values.
my_list = 'apple,banana'.split(',') print(my_list) # ๐๏ธ ['apple', 'banana'] a, b = my_list print(a) # ๐๏ธ 'apple' print(b) # ๐๏ธ 'banana'
The str.split() method splits the string into a list of substrings using a delimiter.
The method takes the following 2 parameters:
Name | Description |
---|---|
separator | Split the string into substrings on each occurrence of the separator |
maxsplit | At most maxsplit splits are done (optional) |
str.split()
method, it splits the input string on one or more whitespace characters.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.
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.
You can learn more about the related topics by checking out the following tutorials: