Rearranging a function for lists to work backwards

Viewed 44
price_list = [["apple", 1], ["sugar", 5], ["mango", 3],["coffee", 9], ["trail mix", 6]]

def most_expensive_item(list):
    result = max(price_list, key=lambda x: x[1])
    return result[0]

I have the code above, but I have run into a bit of a problem. Lets say coffee and sugar are both $9, I want the function to return the item nearest to the end so it would be coffee, like this:

price_list = [["apple", 1], ["sugar", 9], ["mango", 3],["coffee", 9], ["trail mix", 6]]

most_expensive(price_list)
>>> coffee

I feel like theres an easy solution but I'm not seeing it, any help would be appreciated.

2 Answers

So you may easily achieve that by reversing the array

def most_expensive(li):
    result = max(li, key=lambda x: x[1])
    return result[0]

price_list = [["apple", 1], ["sugar", 9], ["mango", 3],["coffee", 9], ["trail mix", 6]]

most_expensive(price_list[::-1])

Or just use the conventional loop:

def most_expensive(list):
    maxi = price_list[-1]
    for i in range(len(price_list)-1, 0, -1):
        if price_list[i][1] > maxi[1]:
            maxi = price_list[i]
    return maxi[0]

most_expensive(price_list)

max() tiebreaks by picking the first element in the sequence that is involved in the tie. If you want the last element, reverse the list and put that into max() instead:

most_expensive(price_list[::-1])
Related