How to find the maximum value in a list of tuples?

PythonListTuples

Python Problem Overview


I have a list with ~10^6 tuples in it like this:

[(101, 153), (255, 827), (361, 961), ...]
  ^     ^
  X     Y

I want to find the maximum value of the Ys in this list, but also want to know the X that it is bound to.

How do I do this?

Python Solutions


Solution 1 - Python

Use max():

 
Using itemgetter():

In [53]: lis=[(101, 153), (255, 827), (361, 961)]

In [81]: from operator import itemgetter

In [82]: max(lis,key=itemgetter(1))[0]    #faster solution
Out[82]: 361

using lambda:

In [54]: max(lis,key=lambda item:item[1])
Out[54]: (361, 961)

In [55]: max(lis,key=lambda item:item[1])[0]
Out[55]: 361

timeit comparison:

In [30]: %timeit max(lis,key=itemgetter(1))
1000 loops, best of 3: 232 us per loop

In [31]: %timeit max(lis,key=lambda item:item[1])
1000 loops, best of 3: 556 us per loop

Solution 2 - Python

In addition to max, you can also sort:

>>> lis
[(101, 153), (255, 827), (361, 961)]
>>> sorted(lis,key=lambda x: x[1], reverse=True)[0]
(361, 961)

Solution 3 - Python

You could loop through the list and keep the tuple in a variable and then you can see both values from the same variable...

num=(0, 0)
for item in tuplelist:
  if item[1]>num[1]:
    num=item #num has the whole tuple with the highest y value and its x value

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBerk ÖzbalcıView Question on Stackoverflow
Solution 1 - PythonAshwini ChaudharyView Answer on Stackoverflow
Solution 2 - PythonBurhan KhalidView Answer on Stackoverflow
Solution 3 - PythonCoffeeRainView Answer on Stackoverflow