Find the element that has the largest second element in nested list

Viewed 137

I have a list like this:

 car_cost = [[carA, 10000], [carB, 20000], [carC, 30000]]

how can I effectively find the element that has the maximum second element?

in this case should be getting a index 2, or the element

[carC, 30000]

I can find the max second element value by

 max(car_cost, key = lambda x:x[1]) 

But I don't know how to do the rest effectively, please show me how can I do this

Thank you very much!!!

3 Answers

max(car_cost, key = lambda x:x[1]) return a list with the car and the number. You can get it with index 0

item = max(car_cost, key=lambda x: x[1])
print(item[0]) # carC

@Guy has the simplest answer, but you can also do:

print(next(iter(max(car_cost, key=lambda x: x[1]))))

Or one-liner version of @Guy's solution:

print(max(car_cost, key=lambda x: x[1])[0])

following the logic you propose, this would be a possible solution.

We get the maximum element in a copy list, and we delete it and again we look for the maximum. Obviously this is not the most profitable but serves to get out of the way.

I recommend you read the following article. It will help you understand the correct logic.

https://www.geeksforgeeks.org/python-program-to-find-second-largest-number-in-a-list/

And here is code:

carA = 1
carB = 2
carC = 3

car_cost = [[carA, 10000], [carB, 20000], [carC, 30000]]
copy = car_cost
copy.remove(max(car_cost, key = lambda x:x[1]))
print(max(copy, key = lambda x:x[1]))
Related