Python - How to sort a list of lists by the fourth element in each list? [duplicate]
unsorted_list.sort(key=lambda x: x[3])
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']]