sort python list by multiple elements

How to Sort Python List By Multiple Elements

Python Lists are powerful data structures that support plenty of functions and features. Often python developers even employ list of lists to store data. Sometimes you may need to sort python list by multiple elements. In this article, we will learn how to sort such python lists using multiple sort keys.

How to Sort Python List By Multiple Elements

Let us say you have the following python list of lists.

s = [[12, 'joe', 'blue', 1],
[2, 'jim', 'red', 9],
[4, 'joe', 'blue', 13]]

Let us say you want to sort the above list of lists using 2 elements – name (jim/joe) and color, that is, the second and third element with index 1 and 2 respectively. You can easily do this using sorted() function.

s = sorted(s, key = lambda x: (x[1], x[2]))

In the above code, we pass 2 arguments to sorted function. The first argument is the list to be sorted and the second argument is the sort key. We us lambda to specify a tuple of keys consisting of 2nd and 3rd element.

Alternatively, you can also use itemgetter() function in second argument to do the same thing.

import operator
s = sorted(s, key = operator.itemgetter(1, 2))

Please note, itemgetter() function is generally faster than using lambda and it also avoids a function call.

You can also use the builtin sort() function available for each Python list as shown below.

s.sort(key = operator.itemgetter(1, 2))

If you want to sort your list by another set of elements, replace 1 and 2 above with index of your desired fields.

In this article, we have learnt how to sort python list by multiple elements.

Also read:

How to Remove Duplicates in Python
How to Check if String is Integer in Python
How to Shuffle List of Objects in Python
How to Find Local IP Address in Python
How to Fix ValueError: Invalid Literal Object Error

Leave a Reply

Your email address will not be published.