alvas
alvas

Reputation: 122042

Find max of the 2nd element in a tuple - Python

Given a tuple list, i can find the max of the 1st element in the tuple list by:

>>> a,b,c,d = (4,"foo"),(9,"bar"),(241,"foobar"), (1,"barfoo")
>>> print max([a,b,c,d])
(241,"foobar")

But how about finding the max of the 2nd element? and how about the max of a string?

Upvotes: 4

Views: 1222

Answers (2)

Olaf
Olaf

Reputation: 41

Even shorter is to use a lambda as the callable

max([a, b, c, d], key=lambda t: t[1])

Upvotes: 4

Martijn Pieters
Martijn Pieters

Reputation: 1121744

Use the key parameter:

import operator

max([a, b, c, d], key=operator.itemgetter(1))

The max() of a string is based on the byte values of the string; 'a' is higher than 'A' because ord('a') is higher than ord('A').

For your example input, (241,"foobar") is still the max value, because 'f' > 'b' and 'foobar' is longer (more values) than 'foo', and 'b' > '' (with b being the character following the letters foo in the longer string).

Upvotes: 6

Related Questions