Python sort list of objects by Properties[with Examples]
Table of Contents
Table of Contents
Introduction to Python sort list of objects by properties
Sorting is the process of arranging items in a specific order. We can sort the items based on certain criteria such as numerical or alphabetical order.
For many applications, there will be a list of objects that need to be sorted based on certain criteria.
The list of objects in python is sorted and it will be useful for many scenarios, i.e:
- For the user interface it needs to display the list of objects in the sorted order, so that users can easily interact with what they are looking for.
- It is very important to sort the list of objects for many algorithms for working it effectively and for improving the performance.
- If there is a list of data points represented as objects, we may want to sort them by a particular attribute before analysing them.
- For generating a report that lists a set of objects in a specific order, it need to sort the list based on certain attributes.
List is a special datatype in python that will store multiple values and it can contain any datatype like string, integer, float etc. We can add and remove values from a list so that is why the list is called mutable.
This is an example of a list:
lst = [ 1, 1.2, "fruits", [ 1, 2, 3 ], {"key":"value"} ]
In list each element is an object is called list of objects. we can see an example below:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
school = [Student("Alan", 10), Student("Ben", 7), Student("Rose", 12)]
In this example, we defined a Student class that has name, age as attributes. We then created a list called school that contains three instances of the Person class.
We can see how to sort the list of objects in python based on different criteria
1. Sorting a list of objects by id
Python has an inbuilt function called “id()”, every object in python has a unique id. For sorting a list of objects by id, we can use the “sorted()” function with the key parameter to set id.
We will go with an example,
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
school = [Student("Alan", 10), Student("Ben", 7), Student("Rose", 12)]
sorted_school = sorted(school, key=id)
for student in sorted_school:
print(student.name, student.age)
In this example, we want to sort a list of Student objects by their unique ids. Every object in Python has a unique id, which can be obtained using the built-in function id().
We start by defining the Student class and creating a list of Student objects representing the students in a school.
Next, we use the sorted() function with the key parameter set to id to sort the list of Student objects by their unique ids. This tells the sorted() function to use the id function as the sorting key for the list of Student objects.
Finally, we print the sorted list of students by iterating over the sorted list and printing each student’s name and age attributes.
The output of this code is:
Rose 12
Ben 7
Alan 10
As we can see, the objects are sorted based on their unique ids, which are not related to any of their attributes.
While sorting objects by their ids can be useful in some cases, it’s important to note that the order of the objects in the sorted list is not related to their attributes in any way.
So sorting by id might not always produce the desired order, especially when sorting by other properties of the objects is required.
2. Sorting the list of objects by other properties
Here we are going to sort the student by their age
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
school = [Student("Alan", 10), Student("Ben", 7), Student("Rose", 12)]
sorted_school = sorted(school, key=lambda student: student.age)
for student in sorted_school:
print(student.name, student.age)
In this example, we have a list of Student objects, where each object represents a student and has attributes name and age. We want to sort the list of students by their age attribute.
We start by defining the Student class and creating a list of Student objects representing the students in a school. Next, we use the sorted() function with a lambda function as the key to sort the list of Student objects by their age attribute.
The lambda function takes a student object as input and returns its age attribute. This tells the sorted() function to use the age attribute as the sorting key for the list of Student objects.
Finally, we print the sorted list of students by iterating over the sorted list and printing each student’s name and age attributes.
The output of this code is:
Ben 7
Alan 10
Rose 12
As we can see, the students are sorted in ascending order by their age. This means the youngest student is first in the sorted list, followed by the next oldest, and so on.
3. Sort list of objects by multiple attributes
Sorting a list of objects by multiple attributes involves using the sorted() function with a custom sorting key that takes into account more than one attribute of the objects.
Here’s an example:
class Student:
def __init__(self, name, age, height):
self.name = name
self.age = age
self.height = height
students = [
Student("Tom", 12, 145),
Student("Ben", 10, 135),
Student("Alan", 9, 130),
Student("Rose", 10, 139),
Student("Bella", 9, 125),
Student("Monica", 12, 149)
]
sorted_student = sorted(students, key=lambda student: (student.age, -student.height))
for student in sorted_student:
print(student.name, student.age, student.height)
In the above example, there is a list of Student objects, where each object has attributes name, age, and height. To sort the list of students first by their age attribute, and if two students have the same age, then sort them by their height attribute in descending order.
To achieve this, we use the sorted() function with a lambda function as the sorting key. The lambda function takes a person object as input and returns a tuple of two values: the age attribute and the negative value of the height attribute.
The negative value is used to sort by height in descending order. This tells the sorted() function to sort the list of Student objects first by their age attribute, and then by their height attribute if their ages are the same.
Finally, we print the sorted list of students by iterating over the sorted list and printing each student’s name, age, and height attributes.
The output of this code is:
Alan 9 130
Bella 9 125
Rose 10 139
Ben 10 135
Monica 12 149
Tom 12 145
As we can see, the list of Student objects is sorted first by their age attribute in ascending order, and then by their height attribute in descending order if their ages are the same.
4. Sort list of objects by alphabetically
Sorting a list of objects alphabetically involves using the sorted() function with a custom sorting key that extracts the attribute from the objects that we want to sort alphabetically.
Here’s an example:
class Student:
def __init__(self, name, age):
self.name = name
self.age = age
students = [
Student("Tom", 12),
Student("Ben", 10),
Student("Alan", 9),
Student("Rose", 11),
Student("Bella", 8),
Student("Monica", 13)
]
sorted_student = sorted(students, key=lambda student: student.name)
for student in sorted_student:
print(student.name, student.age)
In this example, there is a list of Student objects, where each object has attributes name and age. We want to sort the list of students by their name attribute alphabetically.
For getting this, we use the sorted() function with a lambda function as the sorting key. The lambda function takes a student object as input and returns the name attribute of the object. This tells the sorted() function to sort the list of Student objects by their name attribute in alphabetical order.
Finally, we print the sorted list of students by iterating over the sorted list and printing each student’s name and age attributes.
The output of this code is:
Alan 9
Bella 8
Ben 10
Monica 13
Rose 11
Tom 12
As we can see, the list of Person objects is sorted by their name attribute in alphabetical order.