Content · Programming · Python

Python Sorting Lists by Multiple Keys

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. See two practical examples, edge cases and common mistakes.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

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 key function that returns a tuple of comparison keys.
  • Department sorts first; last names break ties within each department.
  • Keep the direction of each key clear.
Share this resourceSend this page to someone who may find it useful.