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

  • Introduction to yfinance: Fetching Historical Stock Data in Python
  • Monitoring Volatility and Daily Averages Using cryptocompare
  • Advanced DOM Interactions: XPath and CSS Selectors in Playwright (Python)
  • Automating Strategy Updates and Version Control in freqtrade
  • Setting Up a freqtrade Dashboard for Real-Time Monitoring
  • Deploying freqtrade on a Cloud Server or Docker Environment
  • Optimizing Strategy Parameters with freqtrade’s Hyperopt
  • Risk Management: Setting Stop Loss, Trailing Stops, and ROI in freqtrade
  • Integrating freqtrade with TA-Lib and pandas-ta Indicators
  • Handling Multiple Pairs and Portfolios with freqtrade
  • Using freqtrade’s Backtesting and Hyperopt Modules
  • Developing Custom Trading Strategies for freqtrade
  • Debugging Common freqtrade Errors: Exchange Connectivity and More
  • Configuring freqtrade Bot Settings and Strategy Parameters
  • Installing freqtrade for Automated Crypto Trading in Python
  • Scaling cryptofeed for High-Frequency Trading Environments
  • Building a Real-Time Market Dashboard Using cryptofeed in Python
  • Customizing cryptofeed Callbacks for Advanced Market Insights
  • Integrating cryptofeed into Automated Trading Bots