Unpack python error

The error "too many values to unpack" is common in Python, you might have seen it while working with lists. Let's find out how to fix it.

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!

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
  • 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!

На чтение 5 мин Просмотров 13.3к. Опубликовано 22.11.2021

В этой статье мы рассмотрим из-за чего возникает ошибка ValueError: too many values to unpack и как ее исправить в Python.

Содержание

  1. Введение
  2. Что такое распаковка в Python?
  3. Распаковка списка в Python
  4. Распаковка списка с использованием подчеркивания
  5. Распаковка списка с помощью звездочки
  6. Что значит ValueError: too many values to unpack?
  7. Сценарий 1: Распаковка элементов списка
  8. Решение
  9. Сценарий 2: Распаковка словаря
  10. Решение
  11. Заключение

Введение

Если вы получаете 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 », разобрались в причинах и механизме ее возникновения. Мы также увидели, что этой ошибки можно избежать.

Table of Contents
Hide
  1. What is Unpacking in Python?
    1. Unpacking using List in Python
    2. Unpacking list using underscore
    3. Unpacking list using an asterisk
  2. What is ValueError: too many values to unpack (expected 2)?
  3. Scenario 1: Unpacking the list elements
    1. Error Scenario
    2. Solution
  4. Scenario 2: Unpacking dictionary 
    1. Error Scenarios
    2. 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. 

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.

Get offers and scholarships from top coding schools illustration

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

Email

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:

Venus profile photo

«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!

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:

  1. While unpacking every item from a list, not every item was assigned a variable.
  2. 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!

Понравилась статья? Поделить с друзьями:
  • Unox ошибка ef5
  • Unox ошибка al03
  • Unox ошибка al02
  • Unox коды ошибок пароконвектомат
  • Unox xvc 505e ошибки