How to sort a list of tuples by a given element in python ?

Published: February 05, 2019

DMCA.com Protection Status

Let's consider a list of tuples generated randomly:

>>> import random
>>> l = [(random.randint(0, 100),random.randint(0, 100)) for i in range(10)]
>>> l
[(69, 38), (92, 75), (37, 89), (64, 52), (70, 72), (84, 44), (13, 0), (20, 67), (38, 56), (40, 98)]

to sort the list by the first tuple element, a solution is to use sorted():

>>> sorted(l)
[(13, 0), (20, 67), (37, 89), (38, 56), (40, 98), (64, 52), (69, 38), (70, 72), (84, 44), (92, 75)]

or same

>>> sorted(l, key=lambda x: x[0])
[(13, 0), (20, 67), (37, 89), (38, 56), (40, 98), (64, 52), (69, 38), (70, 72), (84, 44), (92, 75)]

to sort the list by the second tuple element

>>> sorted(l, key=lambda x: x[1])
[(13, 0), (69, 38), (84, 44), (64, 52), (38, 56), (20, 67), (70, 72), (92, 75), (37, 89), (40, 98)]

Note: work also with sort(), except that sort change the original list l:

>>> l.sort(key=lambda x: x[0])
>>> l
[(13, 0), (20, 67), (37, 89), (38, 56), (40, 98), (64, 52), (69, 38), (70, 72), (84, 44), (92, 75)]
>>> l.sort(key=lambda x: x[1])
>>> l
[(13, 0), (69, 38), (84, 44), (64, 52), (38, 56), (20, 67), (70, 72), (92, 75), (37, 89), (40, 98)]

References