Close

2023-09-20

too many values to unpack (expected 2)

too many values to unpack (expected 2)

The error message “too many values to unpack (expected 2)” occurs in Python when you try to unpack more values than the number of variables available to assign them to. Let’s delve into this error, understand why it occurs, and see how to fix it.

Cause of the Error

This error typically arises in tuple unpacking or function returns, where you try assigning a series of values to a smaller number of variables. For instance:

a, b = [1, 2, 3]

In this snippet, three values are in the list, but only two variables to assign them to, resulting in the error.

How to Fix the Error

To fix this error, you need to ensure the number of values you unpack matches the number of variables you assign them to. Here are a couple of solutions:

1. Adjust the Number of Variables

Adjust the number of variables to match the number of values you are unpacking:

a, b, c = [1, 2, 3]

2. Using a Star Expression

Use a star expression to capture the extra values into a list:

a, b, *c = [1, 2, 3, 4, 5]

In this snippet, a will be 1, b will be 2, and c will be [3, 4, 5].

Example in Function Returns

You might also encounter this error when unpacking values returned from a function. If a function returns more values than you have variables to assign them to, you’ll get this error.

1. Adjust the Number of Variables

def func():
    return 1, 2, 3

a, b, c = func()

2. Using a Star Expression

def func():
    return 1, 2, 3, 4, 5

a, b, *c = func()

Summary

To avoid the “too many values to unpack (expected 2)” error in Python, ensure the number of variables matches the number of values being unpacked or use a star expression to handle extra values. Adjusting your code following these principles will prevent this error and keep your unpacking operations functioning smoothly.