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

oldspice picture oldspice · Nov 13, 2010 · Viewed 282.2k times · Source

I have a list of lists. For example,

[
[0,1,'f'],
[4,2,'t'],
[9,4,'afsd']
]

If I wanted to sort the outer list by the string field of the inner lists, how would you do that in python?

Answer

John La Rooy picture John La Rooy · Nov 13, 2010

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