This post will discuss how to sort a list of objects by multiple attributes in Python.

In the previous post, we have seen how to sort a list of objects using a single attribute. This post will discuss how to sort a list of objects using multiple attributes in Python.

1. Using list.sort() function

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. The key specifies a function of one argument to extract a comparison key from each list item, and the list will be sorted in reversed order when the reverse is True.

To illustrate, the following sorts a list of Employee object with some attributes sorted in the natural order, and remaining attributes sorted in the reverse order.

Download  Run Code

 
If you don’t need any attributes sorted in reverse order, consider using the attrgetter() function from the operator module to produce the key.

Download  Run Code

2. Using sorted() function

The list.sort() function modifies the list in-place. To return a new sorted list instance, you can use the sorted() built-in. It accepts the same keyword-only arguments as the list.sort() function.

Download  Run Code

That’s all about sorting a list of objects by multiple attributes in Python.