Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to sort a tuple of custom objects by properties
Python allows us to create custom objects using classes to represent complex data structures. When we have a tuple containing these custom objects, we often need to sort them by specific properties like name, age, or other attributes.
A custom object is an instance of a user-defined class that encapsulates data and behavior specific to our needs. Here's how we define a simple class ?
class Person:
def __init__(self, name, age):
self.name = name
self.age = age
def __repr__(self):
return f"Person('{self.name}', {self.age})"
# Creating objects
person1 = Person("Alice", 25)
person2 = Person("Bob", 30)
print(person1)
Person('Alice', 25)
Using sorted() with Lambda Function
The sorted() function with a key parameter is the most efficient way to sort tuples of custom objects. The key function extracts the property to sort by ?
class Student:
def __init__(self, name, grade):
self.name = name
self.grade = grade
def __repr__(self):
return f"Student('{self.name}', {self.grade})"
# Create tuple of custom objects
students = (
Student("Charlie", 85),
Student("Alice", 92),
Student("Bob", 78)
)
print("Before sorting:")
for student in students:
print(student)
# Sort by name
sorted_by_name = sorted(students, key=lambda s: s.name)
print("\nSorted by name:")
for student in sorted_by_name:
print(student)
# Sort by grade (descending)
sorted_by_grade = sorted(students, key=lambda s: s.grade, reverse=True)
print("\nSorted by grade (descending):")
for student in sorted_by_grade:
print(student)
Before sorting:
Student('Charlie', 85)
Student('Alice', 92)
Student('Bob', 78)
Sorted by name:
Student('Alice', 92)
Student('Bob', 78)
Student('Charlie', 85)
Sorted by grade (descending):
Student('Alice', 92)
Student('Charlie', 85)
Student('Bob', 78)
Using operator.attrgetter()
For better performance with large datasets, use operator.attrgetter() instead of lambda functions ?
import operator
class Employee:
def __init__(self, name, salary, department):
self.name = name
self.salary = salary
self.department = department
def __repr__(self):
return f"Employee('{self.name}', {self.salary}, '{self.department}')"
employees = (
Employee("John", 50000, "IT"),
Employee("Alice", 60000, "HR"),
Employee("Bob", 55000, "IT")
)
# Sort by salary using attrgetter
sorted_by_salary = sorted(employees, key=operator.attrgetter('salary'))
print("Sorted by salary:")
for emp in sorted_by_salary:
print(emp)
Sorted by salary:
Employee('John', 50000, 'IT')
Employee('Bob', 55000, 'IT')
Employee('Alice', 60000, 'HR')
Multiple Sorting Criteria
You can sort by multiple properties by returning a tuple from the key function ?
class Product:
def __init__(self, name, category, price):
self.name = name
self.category = category
self.price = price
def __repr__(self):
return f"Product('{self.name}', '{self.category}', {self.price})"
products = (
Product("Laptop", "Electronics", 1000),
Product("Book", "Education", 20),
Product("Phone", "Electronics", 800),
Product("Pen", "Education", 5)
)
# Sort by category first, then by price
sorted_products = sorted(products, key=lambda p: (p.category, p.price))
print("Sorted by category, then price:")
for product in sorted_products:
print(product)
Sorted by category, then price:
Product('Pen', 'Education', 5)
Product('Book', 'Education', 20)
Product('Phone', 'Electronics', 800)
Product('Laptop', 'Electronics', 1000)
Comparison of Methods
| Method | Performance | Best For |
|---|---|---|
sorted() with lambda |
Good | Simple sorting, single property |
operator.attrgetter() |
Better | Large datasets, performance critical |
| Multiple criteria | Good | Complex sorting requirements |
Conclusion
Use sorted() with lambda functions for simple property-based sorting of custom objects. For better performance or multiple sorting criteria, consider operator.attrgetter() or tuple keys respectively.
