How to sort a list of tuples by the nth element?

7

I have a list of tuples of the form:

[(0, 1), (2, 3), (4, -5), (6, -3)]

I want to sort this list by the second value of each tuple (that is, in case we would have [(4, -5), (6, -3), (0, 1), (2, 3)] . How to do that?

    
asked by anonymous 14.12.2013 / 23:00

1 answer

9

The simplest way is to use key in calling the sort method of the list:

data = [(0, 1), (2, 3), (4, -5), (6, -3)]
data.sort(key=lambda x: x[1])

>>> data
[(4, -5), (6, -3), (0, 1), (2, 3)]

In this way, the 1 element of each tuple will be the sort key. Another option (considered faster ) is to use the itemgetter function of the operator library.

    
14.12.2013 / 23:00