What’s New ?

The Top 10 favtutor Features You Might Have Overlooked

Read More

Sort a List of Objects in Python

  • Jan 24, 2022
  • 5 Minutes Read
  • Why Trust Us
    We uphold a strict editorial policy that emphasizes factual accuracy, relevance, and impartiality. Our content is crafted by top technical writers with deep knowledge in the fields of computer science and data science, ensuring each piece is meticulously reviewed by a team of seasoned editors to guarantee compliance with the highest standards in educational content creation and publishing.
  • By Riddhima Agarwal
Sort a List of Objects in Python

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.

Example:

# create a list
List = ["favTutor", 60, 32.6]
 
# acessing elements of the list
print("Element at the first position: " +List[0])
print("Element at the third position: " +str(List[2]))

 

Output:

Element at the first position: favTutor
Element at the third position: 32.6

 

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.

Method1

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.

Method 2

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.

Method 3

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.

Example:

import operator
 
# define a class
class Item:
    def __init__(self, name, price, discount):
        self.name = name
        self.price = price
        self.discount = discount
   
    def __repr__(self):
        return '{' + self.name + ', ' + str(self.price) + ', ' + str(self.discount) + '}'
 
# create a list of objects
list = [Item("Doritos", 3, 10),
        Item("Crisps & Chips", 5, 3),
        Item("Cheetos", 4.48, 5),
        Item("Cheese Balls", 6.58, 8),
        Item("Pringles", 1.68, 2)]
 
def getKey(obj):
    return obj.name
 
# printing the list before sorting
print("Before sorting:")
print(list)
 
# method 1
list.sort(key= getKey)
print("Sort by Name")
print(list)
 
# method 2
list.sort(key = lambda x : x.price)
print("Sort by price")
print(list)
 
# method 3
list.sort(key = operator.attrgetter('discount'))
print("Sort by discount")
print(list)
 

 

Output:

Before sorting:
[{Doritos, 3, 10}, {Crisps & Chips, 5, 3}, {Cheetos, 4.48, 5}, {Cheese Balls, 6.58, 8}, {Pringles, 1.68, 2}]
Sort by Name
[{Cheese Balls, 6.58, 8}, {Cheetos, 4.48, 5}, {Crisps & Chips, 5, 3}, {Doritos, 3, 10}, {Pringles, 1.68, 2}]
Sort by price
[{Pringles, 1.68, 2}, {Doritos, 3, 10}, {Cheetos, 4.48, 5}, {Crisps & Chips, 5, 3}, {Cheese Balls, 6.58, 8}]
Sort by discount
[{Pringles, 1.68, 2}, {Crisps & Chips, 5, 3}, {Cheetos, 4.48, 5}, {Cheese Balls, 6.58, 8}, {Doritos, 3, 10}]

 

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:

sorted(iterable, /, *, key=None, reverse=False)

 

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

Example:

# create a list of objects
list = [Item("Doritos", 3, 10),
        Item("Crisps & Chips", 5, 3),
        Item("Cheetos", 4.48, 5),
        Item("Cheese Balls", 6.58, 8),
        Item("Pringles", 1.68, 2)]
 
def getKey(obj):
    return obj.name
 
# printing the list before sorting
print("Before sorting:")
print(list)
 
# method 1
sortedByName = sorted(list, key= getKey)
print("Sort by Name")
print(sortedByName)
 
# method 2
sortedByPrice = sorted(list, key = lambda x : x.price)
print("Sort by price")
print(sortedByPrice)
 
# method 3
sortedBydiscount = sorted(list, key = operator.attrgetter('discount'))
print("Sort by discount")
print(sortedBydiscount)
 

 

Output:

Before sorting:
[{Doritos, 3, 10}, {Crisps & Chips, 5, 3}, {Cheetos, 4.48, 5}, {Cheese Balls, 6.58, 8}, {Pringles, 1.68, 2}]
Sort by Name
[{Cheese Balls, 6.58, 8}, {Cheetos, 4.48, 5}, {Crisps & Chips, 5, 3}, {Doritos, 3, 10}, {Pringles, 1.68, 2}]
Sort by price
[{Pringles, 1.68, 2}, {Doritos, 3, 10}, {Cheetos, 4.48, 5}, {Crisps & Chips, 5, 3}, {Cheese Balls, 6.58, 8}]
Sort by discount
[{Pringles, 1.68, 2}, {Crisps & Chips, 5, 3}, {Cheetos, 4.48, 5}, {Cheese Balls, 6.58, 8}, {Doritos, 3, 10}]

 

sort() and sorted() methods can also be used for sorting a tuple in python.

Summary

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.

FavTutor - 24x7 Live Coding Help from Expert Tutors!

About The Author
Riddhima Agarwal
Hey, I am Riddhima Agarwal, a B.tech computer science student and a part-time technical content writer. I have a passion for technology, but more importantly, I love learning. Looking forward to greater opportunities in life. Through my content, I want to enrich curious minds and help them through their coding journey