In this tutorial, we will see what are the different ways to sort objects in Python.

Different ways to Sort Objects in Python?

Here I am going to show you three different ways to sort the objects in python, let’s see one by one.

Create a list of item object to sort it.

Items.py
class Item():
    def __init__(self,id,name,price):
        self.id=id
        self.name=name
        self.price=price

    def __repr__(self):
        return '({},{},${})'.format(self.id,self.name,self.price)

item1 = Item(100,"Mobile",25000)
item2 = Item(200,"Books",17000)
item3 = Item(300,"Pens",12000)
item4 = Item(400,"Laptops",75000)

items = [item1,item2,item3,item4]

1. Sort Objects in Python using a custom function:

Define a custom function to sort python objects by taking the key (key can be anything like id or name or price).

def item_sort(item):
    return item.price
sorted_items = sorted(items,key=item_sort)
sorted_items = sorted(items,key=item_sort,reverse=True) #reverse order
print(sorted_items)

Created a custom sort function and pass this function as a key in sorted function. If you want to sort the reverse order, you can enable the reverse=True attribute to sorted function.

Output:

[(300,Pens,12000), (200,Books,17000), (100,Mobile,25000), (400,Laptops,75000)]

2. Sort Objects in Python using a lambda function:

Lambda anonymous functions are very flexible to use, we can implement them very easily and quickly. Here is the simplest way to sort objects using lambda.

#Using lambda
sorted_items = sorted(items,key=lambda item:item.name)
print(sorted_items)

Sorting Items by their names.

Output:

[(200,Books,17000), (400,Laptops,75000), (100,Mobile,25000), (300,Pens,12000)]

3. Sort Objects in Python using operator module:

Python operator module’s attrgetter gives us a better way to sort the objects in python.

from operator import attrgetter

sorted_items = sorted(items,key=attrgetter("id"))
print(sorted_items)

Output:

[(100,Mobile,25000), (200,Books,17000), (300,Pens,12000), (400,Laptops,75000)]

Recommended: Python list Data structure in depth.

Happy Learning 🙂

About the Author:

Avatar
Founder of onlinetutorialspoint.com Love Java, Python, Shell and opensource frameworks. Follow him on twitter and facebook for latest updates.

Leave A Comment