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:
1 2 3 4 |
class Employee: def __init__(self, name, age): self.name = name self.age = 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:
1 |
employees = [Employee('John', 25), Employee('Anna', 22), Employee('Peter', 28)] |
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:
1 |
employees.sort(key=lambda x: x.age) |
Step 4: Print the Sorted List
After sorting the list, we can iterate over the list and print each object:
1 2 |
for employee in employees: print(employee.name, employee.age) |
Note: This will print the employees in ascending order of their age. To sort in descending order, you can provide the reverse argument:
1 |
employees.sort(key=lambda x: x.age, reverse=True) |
Full Code:
1 2 3 4 5 6 7 8 9 10 11 |
class Employee: def __init__(self, name, age): self.name = name self.age = age employees = [Employee('John', 25), Employee('Anna', 22), Employee('Peter', 28)] employees.sort(key=lambda x: x.age) for employee in employees: print(employee.name, employee.age) |
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.