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.
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.