How to Sort a List of Class Objects in Python

Sorting is a common operation in programming that allows us to arrange data in a certain order. In this tutorial, we will learn how to sort a list of class objects in Python.

Python provides several ways to sort data, including the built-in sort function and the sorted function. However, sorting a list of objects can be slightly more complex and requires an additional step.

Step 1: Define a Class

In Python, a class is defined using the keyword class followed by the class name. The properties and methods of a class are defined in the body of the class. Here, we define a class Employee with two properties name and age:

Step 2: Create a List of Objects

After defining a class, we can create objects of that class. In this step, we will create a list of Employee objects:

Step 3: Use the sort Function to Sort the List

Python’s built-in sort function can sort a list in place. However, it cannot directly sort a list of objects. We need to provide a function or a lambda as a key. Here, we sort the list of employees by age:

Step 4: Print the Sorted List

After sorting the list, we can iterate over the list and print each object:

Note: This will print the employees in ascending order of their age. To sort in descending order, you can provide the reverse argument:

Full Code:

Anna 22
John 25
Peter 28

Conclusions:

In this tutorial, we have learned how to sort a list of class objects in Python. We learned how to define a class,
create a list of objects, use the sort function, and print the sorted list.
This approach can easily be adapted to sort a list of objects based on any attribute or criteria.