Sling Academy
Home/Python/Fixing the ValueError: Too Many Values to Unpack (Expected 2) in Python

Fixing the ValueError: Too Many Values to Unpack (Expected 2) in Python

Last updated: December 31, 2023

Understanding the Error

Receiving a ValueError: too many values to unpack (expected 2) typically indicates that you’re trying to unpack an iterable (like a list or tuple) into two variables, but the iterable contains more than two items. Python expects exactly two items to unpack, but if it encounters more, it raises this error.

Possible Solutions

Ensure Two-Item Iterables

Check your iterable source and ensure you’re providing an iterable with exactly two items. This can mean either adjusting the iterable itself or changing which parts of it you’re unpacking.

Example:

pair = (1, 2)
a, b = pair
print(a, b)  # Prints: 1 2

Ignoring Excess Values

If your iterable contains more than two items, and you are only interested in the first two, you can use underscore (_) as a placeholder for the remaining items. This tells Python to ignore additional values.

Example:

data = (1, 2, 3, 4)
a, b, *_ = data
print(a, b)  # Prints: 1 2

Extended Unpacking

In case you need the first two values and also want to preserve the rest, Python allows for extended unpacking using a star expression (*). Assign the first two values to individual variables and the rest to a list.

Example:

data = (1, 2, 3, 4)
a, b, *rest = data
print(a, b)  # Prints: 1 2
print(rest)  # Prints: [3, 4]

That’s it. Happy coding!

Next Article: Fixing Python UnboundLocalError: Local Variable ‘x’ Accessed Before Assignment

Previous Article: Fixing Python ValueError: Expected Coroutine, Got Function

Series: Common Errors in Python and How to Fix Them

Python

You May Also Like

  • Python Warning: Secure coding is not enabled for restorable state
  • Python TypeError: write() argument must be str, not bytes
  • 4 ways to install Python modules on Windows without admin rights
  • Python TypeError: object of type ‘NoneType’ has no len()
  • Python: How to access command-line arguments (3 approaches)
  • Understanding ‘Never’ type in Python 3.11+ (5 examples)
  • Python: 3 Ways to Retrieve City/Country from IP Address
  • Using Type Aliases in Python: A Practical Guide (with Examples)
  • Python: Defining distinct types using NewType class
  • Using Optional Type in Python (explained with examples)
  • Python: How to Override Methods in Classes
  • Python: Define Generic Types for Lists of Nested Dictionaries
  • Python: Defining type for a list that can contain both numbers and strings
  • Using TypeGuard in Python (Python 3.10+)
  • Python: Using ‘NoReturn’ type with functions
  • Type Casting in Python: The Ultimate Guide (with Examples)
  • Python: Using type hints with class methods and properties
  • Python: Typing a function with default parameters
  • Python: Typing a function that can return multiple types