PYTHON
Sorting Custom Objects by Specific Attributes
Learn to sort lists of custom objects in Python using `list.sort()` or `sorted()` with a `key` argument, leveraging `lambda` functions or `operator.attrgetter` for clarity.
from operator import attrgetter
class Product:
def __init__(self, name, price, stock):
self.name = name
self.price = price
self.stock = stock
def __repr__(self):
return f"Product(name='{self.name}', price={self.price}, stock={self.stock})"
products = [
Product('Laptop', 1200, 10),
Product('Mouse', 25, 50),
Product('Keyboard', 75, 20),
Product('Monitor', 300, 5)
]
print("Original products:")
for p in products:
print(p)
# Sort by price (ascending) using lambda
products.sort(key=lambda p: p.price)
print("
Sorted by price (ascending):")
for p in products:
print(p)
# Sort by stock (descending) using attrgetter
products.sort(key=attrgetter('stock'), reverse=True)
print("
Sorted by stock (descending):")
for p in products:
print(p)
# Sort by name (alphabetical) using attrgetter
products.sort(key=attrgetter('name'))
print("
Sorted by name (alphabetical):")
for p in products:
print(p)
How it works: When working with lists of custom objects, Python's `sort()` method or the `sorted()` built-in function can sort them based on specific attributes. By providing a `key` argument, which can be a `lambda` function or `operator.attrgetter`, you specify which attribute(s) to use for comparison. This allows for flexible and efficient ordering of complex data structures, crucial for displaying or processing structured data.