The Python Oracle

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

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Digital Sunset Looping

--

Chapters
00:00 Question
00:28 Accepted answer (Score 393)
00:51 Answer 2 (Score 243)
01:07 Answer 3 (Score 97)
01:22 Answer 4 (Score 21)
01:37 Thank you

--

Full question
https://stackoverflow.com/questions/4174...

Accepted answer links:
[itemgetter]: http://docs.python.org/library/operator....

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #sorting

#avk47



ACCEPTED ANSWER

Score 399


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




ANSWER 2

Score 259


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])



ANSWER 3

Score 100


Itemgetter lets you to sort by multiple criteria / columns:

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



ANSWER 4

Score 21


multiple criteria can also be implemented through lambda function

sorted_list = sorted(list_to_sort, key=lambda x: (x[1], x[0]))