Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Sorting list of custom class objects by a property in python

I’m having an issue when sorting a list of custom class objects in Python based on one of their properties in Python. I have a list of Product objects (made this class myself as seen below), each with attributes name, price, and rating. I’m trying to sort the list by the price property in ascending order.

Here’s the code I have with key=lambda x: x.price which I found from another question

class Product:
    def __init__(self,name,price,rating):
        self.name=name
        self.price=price
        self.rating=rating

product_list = [
Product("Laptop", 900, 4.5),
Product("Headphones", 100, 4.2),
Product("Keyboard", 50, 4.8),
Product("Monitor", 350, 4.6)
]

sorted(product_list, key=lambda x: x.price)
for product in product_list:
    print(product.name, product.price, product.rating)

However, this code doesn’t seem to sort the list – it’s still in the original order. And the weird thing is I’m not receiving any errors, so I can’t find out where the mistake is.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

Could someone please help me understand what’s happening? Am I using the sorted function incorrectly in this context with the lambda thing? Sorry if this is a noob question.

>Solution :

The issue is that sorted() is not an in-place sort, so you need to assign the result to a variable. sorted() returns a new list, so you can’t just do sorted(product_list, key=lambda x: x.price) and expect product_list to be sorted.

Luckily, it’s an easy fix:

product_list = sorted(product_list, key=lambda x: x.price)
for product in product_list:
    print(product.name, product.price, product.rating)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading