Sometimes, we want to sort a list of lists by a specific index of the inner list with Python.
In this article, we’ll look at how to sort a list of lists by a specific index of the inner list with Python.
How to sort a list of lists by a specific index of the inner list with Python?
To sort a list of lists by a specific index of the inner list with Python, we can use the itemgetter
function.
For instance, we write
from operator import itemgetter
l = [[0, 1, "f"], [4, 2, "t"], [9, 4, "afsd"]]
sorted_l = sorted(l, key=itemgetter(2))
to call sorted
with list l
and the key
argument set to itemgetter
with index 2 to sort list l
by the 3rd item in the list and return the sorted list.
Conclusion
To sort a list of lists by a specific index of the inner list with Python, we can use the itemgetter
function.