Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding max value in the second column of a nested list?

I have a list like this:

alkaline_earth_values = [['beryllium',  4],                           ['magnesium', 12],                          ['calcium',   20],                          ['strontium', 38],                           ['barium',    56],                           ['radium',    88]] 

If I simply use the max(list) method, it will return the answer 'strontium', which would be correct if I was trying to find the max name, however I'm trying to return the element whose integer is highest.

like image 213
davelupt Avatar asked Jan 26 '11 00:01

davelupt


People also ask

How do you find a maximum value in a list?

Method: Use the max() and def functions to find the largest element in a given list. The max() function prints the largest element in the list.

How do you find the max tuple in a list?

Method #1 : Using max() + operator.itemgetter() We can get the maximum of corresponding tuple index from a list using the key itemgetter index provided and then mention the index information required using index specification at the end.

Can we use MAX function in list?

The max() Function — Find the Largest Element of a List. In Python, there is a built-in function max() you can use to find the largest number in a list. To use it, call the max() on a list of numbers. It then returns the greatest number in that list.


1 Answers

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

The reason this works is because the key argument of the max function specifies a function that is called when max wants to know the value by which the maximum element will be searched. max will call that function for each element in the sequence. And lambda x: x[1] creates a small function which takes in a list and returns the first (counting starts from zero) element. So

k = lambda x: x[1] 

is the same as saying

def k(l):   return l[1] 

but shorter and nice to use in situations like this.

like image 168
kynnysmatto Avatar answered Oct 07 '22 16:10

kynnysmatto