Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How do you sort a list by its second element?

Use the key argument of the sorted() function to sort a list of tuples by the second element, e.g. sorted_list = sorted(list_of_tuples, key=lambda t: t[1]) . The function will return a new list, sorted by the second tuple element.

How do you sort a list within a list Python?

Use the sort() Function to Sort a List of Lists in Python. The sort() method sorts the list of lists in Python according to the first element of each inner list. This method makes changes in the original list itself. We use the reverse parameter to sort in descending order.

How do you sort a list by multiple attributes in Python?

A Pythonic solution to in-place sort a list of objects using multiple attributes is to use the list. sort() function. It accepts two optional keyword-only arguments: key and reverse and produces a stable sort.


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']]