35
votes

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.

4
The answers here are perfectly good, but it may also be worth checking out a similar question, which was closed as being a duplicate of this one but nevertheless has some useful answers that are not the same as these. - John Y
max(alkaline_earth_values) actually returns ['strontium', 38], so it's giving you both the name and value pair with the maximum value. - martineau

4 Answers

73
votes
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.

7
votes

Use the key argument.

max(alk..., key=operator.itemgetter(1))
0
votes

it is rather tricky to assume that an item in a list is actually still a number. If the numbers have become strings, the max() will return the 'value' with the highest first number:

alkaline_earth_values = [['beryllium', '9'], ['magnesium', '12'],['calcium', '20'],
                         ['strontium', '38'], ['barium', '56'], ['radium', '88']]
max(alkaline_earth_values, key=lambda x: x[1])

returns ['beryllium', '9']

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

will do the trick, when you are sure it will be a number

0
votes

For high speed consider pandas or numpy:

Import pandas as pd
alkaline_earth_values = [['beryllium', 4], ['magnesium', 12],['calcium', 20],
                     ['strontium', 38], ['barium', 56], ['radium', 88]]
pd.DataFrame(alkaline_earth_values)[1].max()