Tuple pairs, finding minimum using python

Harry Lime picture Harry Lime · Feb 10, 2013 · Viewed 52k times · Source

I want to find the minimum of a list of tuples sorting by a given column. I have some data arranged as a list of 2-tuples for example.

data = [ (1, 7.57), (2, 2.1), (3, 1.2), (4, 2.1), (5, 0.01), 
         (6, 0.5), (7, 0.2), (8, 0.6)]

How may I find the min of the dataset by the comparison of the second number in the tuples only?

i.e.

data[0][1] = 7.57
data[1][1] = 2.1

min( data ) = (5, 0.01)

min( data ) returns (1, 7.57), which I accept is correct for the minimum of index 0, but I want minimum of index 1.

Answer

Lev Levitsky picture Lev Levitsky · Feb 10, 2013
In [2]: min(data, key = lambda t: t[1])
Out[2]: (5, 0.01)

or:

In [3]: import operator

In [4]: min(data, key=operator.itemgetter(1))
Out[4]: (5, 0.01)