Search code examples
pythonlisttuplesiterable-unpacking

ValueError: too many values to unpack (expected 2) with a list of tuples in Python


I have this issue when creating a code with Python. I pass a list of tuples but when unpacking it and then using the map function and then using a list. I get this Error:

ValueError: too many values to unpack (expected 2)

Any idea how to overcome this? I can't find a suitable answer yet related to a list of tuples :-(

Here is the code

stock_markets = [('AAPL','200'),('MSFT','780'),('ORCL','650'),('CISC','350')]

def analyze_stocks(stock_markets):
    current_max = 0
    stock_name = ''

    for company,price in stock_markets:
        if int(price) > current_max:
            current_max = int(price)
            stock_name = company
        else:
            pass

    return (stock_name, current_max)

list(map(analyze_stocks,stock_markets))

Solution

  • You're already iterating over your list with map. Your for loop inside the analyze function is not needed (since you're passing your stocks one by one already with map) and it is the source of error. Correct version should be something like this:

    stock_markets = [('AAPL','200'),('MSFT','780'),('ORCL','650'),('CISC','350')]
    
    def analyze_stocks(stock_markets):
        current_max = 0
        stock_name = ''
    
        company, price = stock_markets
        if int(price) > current_max:
            current_max = int(price)
            stock_name = company
    
        return (stock_name, current_max)
    
    list(map(analyze_stocks,stock_markets))