There seems to be a constant requirement to sort and manipulate custom objects by some property, which is why we've written this article. To show how to sort an object list by a certain property using a custom list of objects. But before that let us have a quick recap of what a list is in python.
What is a List?
If you are familiar with arrays in different programming languages then the concept of lists will come naturally to you. The list is one of the built-in data types in python, which is used to store a collection of data. We think of lists as dynamically sized arrays, which can store heterogeneous data as well. By dynamically sized arrays, what we mean is that the size of the lists can change during the runtime. Lastly, lists have the property of being mutable, meaning we can alter lists even after creating them. Just like an array, the elements of a list are indexed, with the index of the first element being 0.
How to Sort a List of Objects in Python?
We are already familiar with how we can sort a list of integers, strings, etc. In this section, we will learn how we can sort list of objects in python. Objects are instances of a class. There are two major methods by which we can sort. We have discussed both the methods in every detail so that you can have thorough knowledge about them.
1) Using sort() method
This is a simple method, using it we can sort a collection of objects with the help of some attributes in Python. This function generates a stable sort by sorting the list inplace. By in-place sort means that the changes are done to the original list and no new auxiliary list is created to fulfill the purpose. The signature of this method is :
sort(*, key=None, reverse=False)
This method accepts two arguments:
Key: This is a single argument function, that extracts a comparison key from each list object. In other words, this is a function to get the attribute according to which sorting is to be done. This argument is optional
Reverse: This optional argument if set to True, sorts the list in descending order.
Let us now look at an example, so that we can understand the sort() method better. In the code below we have defined a class called Item to represent different products in a shop. The Item class has 3 attributes:
name: Name of the product
price: the selling price of the product
discount: discount on the product
In the example we have shown three different methods, using which we can produce a value for the key attribute.
This method makes use of a user-defined function, which takes an object as the argument and returns the name attribute of that object. Since the key attribute gets the name attribute as its value, therefore the list gets sorted according to the name of different products.
This method uses a lambda function. In all other manners, it is the same as the previous method. The lambda function gets the price attribute of an Item object.
There is a method called operator.attrgetter(), in the operator module. This method returns a callable object that fetches a specified attribute from its operand. The attrgetter() method can be used to generate a value for the key parameter.
2) Using sorted() method
This List.sort() method does not return any sorted list, instead, it makes changes to the original list itself. On the other hand, the sorted() method returns a new sorted list and leaves the original list unchanged. The method syntax of the sorted() method looks like this:
This method takes an iterable as one of its arguments. In our case, Iterable is the list of objects that we want to be sorted. Apart from this, the sorted function can take two optional arguments: key and reverse.
Key: It specifies a one-argument function that is used to extract a comparison key from each element in the iterable. The default value is None, which stands for comparing the elements directly.
reverse: This optional argument if set to True, sorts the list in descending order.
Just like the example discussed in the list.sort() method, we can provide a function to the key attribute in three different manners. We also used the same class as we used in the previous example
sort() and sorted() methods can also be used for sorting a tuple in python.
Sorting algorithms have been a huge topic for research. There is a constant race for finding the best algorithm that can sort data in minimum time and space. In this article, we look at a few ways in which we can sort a list of objects in python. There are several other sorting algorithms available, we request you read them once.