Sorting with Custom Callbacks
Introduction to Custom Sorting
Python provides powerful sorting mechanisms that allow developers to customize sorting behavior using callback functions. The key methods for implementing custom sorting are sort()
and sorted()
.
Basic Sorting Methods
## Default sorting
numbers = [5, 2, 8, 1, 9]
sorted_numbers = sorted(numbers) ## [1, 2, 5, 8, 9]
## List sorting methods
numbers.sort() ## In-place sorting
Custom Sorting with Key Function
## Sorting with key callback
students = [
{'name': 'Alice', 'grade': 85},
{'name': 'Bob', 'grade': 92},
{'name': 'Charlie', 'grade': 78}
]
## Sort by grade
sorted_students = sorted(students, key=lambda x: x['grade'])
Sorting Callback Types
flowchart TD
A[Sorting Callbacks] --> B[Key Function]
A --> C[Comparison Function]
B --> D[Transform Data]
C --> E[Custom Comparison Logic]
Advanced Sorting Techniques
Reverse Sorting
## Reverse sorting
numbers = [5, 2, 8, 1, 9]
reverse_sorted = sorted(numbers, reverse=True) ## [9, 8, 5, 2, 1]
Complex Sorting Scenarios
## Multi-level sorting
data = [
('John', 25, 'Engineering'),
('Alice', 22, 'Computer Science'),
('Bob', 25, 'Mathematics')
]
## Sort by age, then by name
sorted_data = sorted(data, key=lambda x: (x[1], x[0]))
Sorting Callback Strategies
Strategy |
Description |
Use Case |
Lambda Functions |
Inline, simple transformations |
Quick, one-time sorting |
Defined Functions |
Complex logic, reusable |
Sophisticated sorting rules |
Operator Methods |
Standard transformations |
Efficient, built-in operations |
import operator
## Efficient sorting with operator
students = [
{'name': 'Alice', 'grade': 85},
{'name': 'Bob', 'grade': 92}
]
## Using operator.itemgetter for performance
sorted_students = sorted(students, key=operator.itemgetter('grade'))
Common Sorting Patterns
- Sorting by multiple criteria
- Case-insensitive sorting
- Sorting complex objects
- Handling None values
At LabEx, we emphasize understanding these sorting techniques to write more flexible and efficient Python code.