This post will discuss how to sort a list of objects using an attribute in Python.

1. Using list.sort() function

A simple solution is to use the list.sort() function to sort a collection of objects (using some attribute) in Python. This function sorts the list in-place and produces a stable sort.

It accepts two optional keyword-only arguments: key and reverse. The key argument specifies a single-arg function to extract a comparison key from each list object. When the reverse argument is True, the list will be sorted in reversed order.

To illustrate, the following sorts a list of Employee objects using the name attribute in the natural order, followed by the reverse order.

Download  Run Code

 
You can also use the operator.attrgetter() function to produce value for the key attribute. It returns a callable object that fetches a specified attribute from its operand.

Download  Run Code

2. Using sorted() function

The list.sort() function does not return the sorted sequence but modifies the list in-place. To return a new sorted list instance, you can use the sorted() built-in function. Like the list.sort() function, it accepts two optional keyword-only arguments – key and reverses – that have the same meaning. The following example demonstrates.

Download  Run Code

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

 
Also See:

Sort a list of objects by multiple attributes in Python