How to sort a list of lists by a specific index of the inner list? How to sort a list of lists by a specific index of the inner list? python python

How to sort a list of lists by a specific index of the inner list?


This is a job for itemgetter

>>> from operator import itemgetter>>> L=[[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]>>> sorted(L, key=itemgetter(2))[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]

It is also possible to use a lambda function here, however the lambda function is slower in this simple case


in place

>>> l = [[0, 1, 'f'], [4, 2, 't'], [9, 4, 'afsd']]>>> l.sort(key=lambda x: x[2])

not in place using sorted:

>>> sorted(l, key=lambda x: x[2])


Itemgetter lets you to sort by multiple criteria / columns:

sorted_list = sorted(list_to_sort, key=itemgetter(2,0,1))