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

Posted on

Solving problem is about exposing yourself to as many situations as possible like How to sort a list of lists by a specific index of the inner list? and practice these strategies over and over. With time, it becomes second nature and a natural way you approach any problems in general. Big or small, always start with a plan, use other strategies mentioned here till you are confident and ready to code the solution.
In this post, my aim is to share an overview the topic about How to sort a list of lists by a specific index of the inner list?, which can be followed any time. Take easy to follow this discuss.

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

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?

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

multiple criteria can also be implemented through lambda function

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

``````array.sort(key = lambda x:x[1])
``````

You can easily sort using this snippet, where 1 is the index of the element.

Like this:

``````import operator
l = [...]
sorted_list = sorted(l, key=operator.itemgetter(desired_item_index))
``````

I think lambda function can solve your problem.

``````old_list = [[0,1,'f'], [4,2,'t'],[9,4,'afsd']]
#let's assume we want to sort lists by last value ( old_list[2] )
new_list = sorted(old_list, key=lambda x: x[2])
#Resulst of new_list will be:
[[9, 4, 'afsd'], [0, 1, 'f'], [4, 2, 't']]
``````

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