How to sort a list/tuple of lists/tuples by the element at a given index? How to sort a list/tuple of lists/tuples by the element at a given index? python python

How to sort a list/tuple of lists/tuples by the element at a given index?


sorted_by_second = sorted(data, key=lambda tup: tup[1])

or:

data.sort(key=lambda tup: tup[1])  # sorts in place


from operator import itemgetterdata.sort(key=itemgetter(1))


For sorting by multiple criteria, namely for instance by the second and third elements in a tuple, let

data = [(1,2,3),(1,2,1),(1,1,4)]

and so define a lambda that returns a tuple that describes priority, for instance

sorted(data, key=lambda tup: (tup[1],tup[2]) )[(1, 1, 4), (1, 2, 1), (1, 2, 3)]


matomo