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

Python raises ValueError if a function receives arguments with an incorrect type but a valid value. Python valueerror: Too many values to unpack (expected 2). This means that you are trying too many values from an iterator. This tutorial will explain what unpacking is and give examples of how to fix it.

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

Python raises ValueError if a function receives arguments with an incorrect type but a valid value. Python valueerror: Too many values to unpack (expected 2). This means that you are trying too many values from an iterator.

This tutorial will explain what unpacking is and give examples of how to fix it.

Python valueerror: Too many values to unpack (expected 2).

Python functions can return multiple variables. These returned values are stored in variables. If there aren't enough objects to assign to the variables, the valueerror is raised.

What is unpacking?

Unpacking is a process that assigns a set of values to a tuple, or a list variables, in one assignment. Unpacking can be complemented by packing, which is the collection of multiple values in one variable. The unpacking operator can be used in this context.

*

Multiple variables can be collected or packed into one variable. The * operator will be used to pack a tuple with three values into one variable.

# Combine three values into one variable

*x, = 1, 2, 3

print(x)

[1, 2, 3]

The left side must contain a tuple, or a list. This means that we will need to use a trailing colon. We will raise SyntaxError if we don't use a trailing colon. The starred assignment target must be within a list, tuple or tuple.

Let's take a look at how to unpack in Python.

Unpacking with List and Tuple

Python places the tuple variable on the left side assignment operator

=

A tuple of values on each side. The variables on the left will get the values from the right by using their positions in the tuple. This operation can be applied to any iterable, not just to tuples. Because they make code easier to read, unpacking operations can be very useful.

# Tuple unpacking example

(a, b, c) = (1, 2, 3)

# Print results

print(a)

print(b)

print(c)

1

2

3

We don't need to use two parentheses for delimiters when creating a tuple object. The following syntaxes can be used:

# A different syntax is used to unpack a tuple or assign variables

(a, b, c) = 1, 2, 3

A, b and c = (1. 2, 3)

A, b, and c = 1, 2, 3,

Let's take an example of how to unpack a list.

# Unpack a list and assign three variables

d, E, f = [4, 5, 6,]

print(d)

print(e)

print(f)

4

5

6

If we use three values on each side, and two variables on each side, we raise a ValueError. This tells us that we have too many values to decode.

# Attempting to assign three values for two variables

A, b = 1, 2, 3,

---------------------------------------------------------------------------

ValueError Traceback (most recently called last)

In

----> 1a, b = 1, 2, 3,

ValueError: Too many values to unpack (expected 2

If you use more variables than value, you will get a ValueError indicating that there aren't enough values to unpack.

# Trying assigning two values to three variables

a,b,c = 1, 2,

---------------------------------------------------------------------------

ValueError Traceback (most recently called last)

In

----> 1a, b and c = 1, 2,

ValueError - Not enough values to unpack (expected 3, got 2)

Asterisk: Unpacking

The packing operator can be used

*

To group variables in a list. Let's say we have more variables than elements in a list. The packing operator will add the extra elements to a list and assign them to the last variable. Let's take a look at unpacking with *:

# Use the asterisk to unpack lists with more values than variables

x, y, *z = [2, 4, 8, 16, 32]

print(x)

print(y)

print(z)

2

4

[8, 16, 32]

When a function receives multiple arguments, the asterisk can be used. We will raise a TypeError if we pass a list to a function which requires multiple arguments without unpacking.

# Create a function that takes three arguments and prints them on the console

def print_func(x, y, z):

print(x, y, z)

num_list = [2, 4, 6]

print_func(num_list)

---------------------------------------------------------------------------

TypeError Traceback (last call)

In

----> 1 print_func(num_list)

TypeError: print_func() is missing two required positional arguments: "y" and "z".

Functions expect three arguments. However, num_list can be used as a single argument. We unpack the list before passing it to print_func in order to resolve the TypeError.

# Create a function that takes three arguments and prints them on the console

def print_func(x, y, z):

print(x, y, z)

num_list = [2, 4, 6]

# To unpack the list, use the asterisk

print_func(*num_list)

2 4 6

Three mistakes can cause valueerror: Too many values to unpack (expected 2:

  • Try to trawl through a dictionary, and then unpack its key and value separately
  • It is not possible to assign every element of a list as a variable
  • Try to. When using functions, don't try to unpack too many values

Example 1: Iterating over a Dictionary

A dictionary in Python is a collection of key-value pairs that store unordered items. Consider a dictionary called muon_particle that contains information about the muon. The dictionary is composed of three keys: name, mass, charge. Each key is assigned a value. This value is written on the right side of each key, separated by a colon.

# An example of a dictionary

muon_particle = {

'name' : 'muon',

'mass' : 105.66,

'charge' : -1,

}

# Iterate over dictionary

For keys and values in muon_particle, click here

print(keys, values)

---------------------------------------------------------------------------

ValueError Traceback (last call)

In

----> 1 to find keys and values in muon_particle

2 print(keys, values)

3

ValueError: Too many values to unpack (expected 2

Because each item in the

muon_particle

Dictionary is a value. Keys and values are not different values in the dictionary.

Solution

To solve the error, we include the items() method into the for loop. This method analyses a dictionary and returns keys and values as tuples. Let's change it and see what happens.

# Iterate over dictionary 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)])

Our online Python compiler allows you to test your Python code.

Example 2: Unpacking a list to a variable

If the number or elements of a list that we are trying to unpack to a variable is not equal to the number assigned variables, the ValueError will be raised. Let's say we have a five-page list. However, there are only two variables left of the assignment operator.

# Unpacking a List to Variables

x, y = ['we', 'love', 'coding', 'in', 'Python']

---------------------------------------------------------------------------

ValueError Traceback (most recently called last)

In

----> 1 x, y = ['we', 'love', 'coding', 'in', 'Python']

ValueError: Too many values to unpack (expected 2

It is important to make sure that the number and type of variables we wish to unravel equals the number and types of elements in the table.

Solution

It is important to ensure that there are at least five variables for the list to be unpacked.

# Unpacking the 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: Too many Values Unpacking While Using Functions

When calling functions, we can raise the ValueError. Let's take a look at the input() function. It takes input from the user and returns a string value. The variable is then assigned to it. This will give the input() function a name and a second name in one string. The program will assign the input to one of two variables: first and last names.

# Use input function to return string object and to assign it to two variables

input ('Enter your full name:' first_name, last_name = input

Please enter your full name: Richard Feynman

---------------------------------------------------------------------------

ValueError Traceback (most recently called last)

In

----> 1 last_name, first_name = input ('Enter your full name:').

ValueError: Too many values to unpack (expectant 2)

We raise the ValueError as the interpreter expects two value, but we return the input string as one.

Solution

The can be used

split()

Function to resolve this error. It returns a list with substrings for a given string. Learn more about substrings in Python by reading the article "How to Get Substrings From Strings". The default delimiter space is used to create the substring. Let's examine split() as a solution to the error.

# Use input function to return string object, and split() function to assign two variables to it

input ('Enter full name :').split()

print(first_name)

print(last_name)

Richard

Feynman

Summary

You made it to the end! When you don't unpack all items on a list, the ValueError: Too Many Values to Unpack (expected 2)" will occur.

It is a common error to try to convert too many values into variables. This can be solved by making sure that the number of variables is equal to the number items on the list.

This error can also occur when you try to iterate over items in a dictionary. This error can be fixed by using the

items()

Method to iterate over the dictionary.

You should ensure that you assign the same number of variables to a function that returns multiple values.

If you are passing a list to a program and it expects more than one argument you can use unpacking the list.

*

When passing the list to the function.