A team roster should sort by department, then last name.
What You Need to Understand
Sort structured records with a key function that returns a tuple of comparison keys. Tuple keys are compared from left to right, enabling multi-level sorting.
When to Use It
A team roster should sort by department, then last name.
Step-by-Step Python Example
employees = [("Support", "Miller"), ("IT", "Smith"), ("IT", "Adams")]
ordered = sorted(employees, key=lambda employee: (employee[0], employee[1]))
print(ordered)
How the Example Works
Department sorts first; last names break ties within each department.
Example Output
[('IT', 'Adams'), ('IT', 'Smith'), ('Support', 'Miller')]
[('C', 2), ('A', 3), ('B', 3)]
A Second Example
Compare this smaller variation with the main example, then experiment with your own values.
products = [("B", 3), ("A", 3), ("C", 2)]
print(sorted(products, key=lambda product: (product[1], product[0])))
Important Behavior and Edge Cases
Keep the direction of each key clear. For mixed ascending and descending numeric keys, negate only the numeric component rather than trying to reverse everything.
Try It Yourself
Sort product records by price and then name.
Common Beginner Mistakes
- Keep the direction of each key clear. For mixed ascending and descending numeric keys, negate only the numeric component rather than trying to reverse everything.
- Overlooking how an iterable is consumed, how element positions are chosen, or whether a function creates a new list.
Key Takeaways
- Sort structured records with a
keyfunction that returns a tuple of comparison keys. - Department sorts first; last names break ties within each department.
- Keep the direction of each key clear.