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

Asked

Viewed 4,345 times

9

I have a list of fashion tuples:

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

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

1 answer

12


The simplest way is to use key in the call to method sort 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)]

Thus, the element 1 of each tuple will be the sorting key. Another option considered fastest is to use the function itemgetter library operator.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.