max() of a list of tuples

Alan Daniels from_deja at alandaniels.com
Thu Jan 23 15:37:49 EST 2003


Max M <maxm at mxm.dk> wrote in message news:<3E2D2E46.6060104 at mxm.dk>...

> l = [(1,3,5), (8,16,2), (2,56,4)]
> print max([(i[-1],i) for i in l])[1]

Another possible solution, using a slightly different route:

  best = max([x[-1] for x in l])
  print [x for x in l if x[-1] == best][0]

Line one: Find the max value for the last item in each of the tuples.
Line two: Get the tuple that has that max value.

Slightly less efficient, since it uses two list comprehensions, and thus
traverses the lists twice, but easier to understand at first glance, imho.




More information about the Python-list mailing list