Python - How to sort a list of lists by the fourth element in each list?

PythonListSorting

Python Problem Overview


I would like to sort the following list of lists by the fourth element (the integer) in each individual list.

unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]

How can I do this? Thank you!

Python Solutions


Solution 1 - Python

unsorted_list.sort(key=lambda x: x[3])

Solution 2 - Python

Use sorted() with a key as follows -

>>> unsorted_list = [['a','b','c','5','d'],['e','f','g','3','h'],['i','j','k','4','m']]
>>> sorted(unsorted_list, key = lambda x: int(x[3]))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

The lambda returns the fourth element of each of the inner lists and the sorted function uses that to sort those list. This assumes that int(elem) will not fail for the list.

Or use itemgetter (As Ashwini's comment pointed out, this method would not work if you have string representations of the numbers, since they are bound to fail somewhere for 2+ digit numbers)

>>> from operator import itemgetter
>>> sorted(unsorted_list, key = itemgetter(3))
[['e', 'f', 'g', '3', 'h'], ['i', 'j', 'k', '4', 'm'], ['a', 'b', 'c', '5', 'd']]

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionDana GrayView Question on Stackoverflow
Solution 1 - PythonTaymonView Answer on Stackoverflow
Solution 2 - PythonSukrit KalraView Answer on Stackoverflow