Computing argmax in Python

Which fruit is the most frequent in this basket?


In [1]:
basket = [("apple", 12), ("pear", 3), ("plum", 14)]
max(basket, key=lambda pair: pair[1])


Out[1]:
('plum', 14)

Returns a tuple, let's get its first element.


In [2]:
max(basket, key=lambda pair: pair[1])[0]


Out[2]:
'plum'

Most common element

Which item appears most times in this list?


In [3]:
basket = ["apple", "apple", "plum", "pear", "plum", "plum"]
max((basket.count(fruit), fruit) for fruit in set(basket))[1]


Out[3]:
'plum'

Second solution


In [4]:
max(set(basket), key=basket.count)


Out[4]:
'plum'

Highest element's index

Which coordinate is the highest in this vector?


In [5]:
vec = [2.3, -1, 0, 3.4, 1]
max((v, i) for (i, v) in enumerate(vec))[1]


Out[5]:
3