Sort a list by multiple attributes?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
Sorting by multiple attributes is a common requirement when records have several ranking rules. Typical examples are sorting people by department then salary, or products by category then price. Python makes this straightforward with tuple-based keys and stable sorting.
Sort with a Tuple Key
In Python, sorted and list.sort accept a key function. When that function returns a tuple, Python compares tuple elements from left to right.
This sorts by team first, then level, then salary.
Mix Ascending and Descending Rules
One common need is ascending for some fields and descending for others. Numeric fields can be negated in the key for descending behavior.
For text fields requiring descending order, perform multi-pass stable sorts.
Because Python sort is stable, earlier order for equal keys is preserved.
Sort Objects and Dataclasses
With objects, use attrgetter for cleaner key expressions.
This style scales better than long lambda expressions when attributes grow.
Handle Missing Values Explicitly
Real data often has missing fields. Define a key that pushes missing values to the end.
This avoids runtime errors and makes your rule intentional.
Locale and Case Handling for Text Fields
Text sorting can vary when case and locale matter. Normalize case in the key when you need predictable ordering.
For locale-sensitive business output, use locale-aware transforms consistently across services and reports.
In-Place vs New List
Use sorted when you need a new list and want to preserve input order for other consumers. Use list.sort when mutating in place is acceptable and memory savings matter. Choosing explicitly helps prevent accidental side effects in shared data structures used across multiple functions.
Testing Multi-Attribute Sort Rules
Sorting bugs are easy to miss because output may still look mostly correct. Add focused tests that verify tie-breaking order.
Tests like this protect ranking behavior from accidental changes.
Common Pitfalls
- Mixing ascending and descending requirements without documenting key rules causes confusion.
- Relying on implicit missing-value behavior can produce unstable or surprising ordering.
- Using custom comparison functions instead of keys is slower and harder to maintain.
- Sorting repeatedly in loops can become a major performance bottleneck.
- Forgetting sort stability properties can lead to unnecessary complex code.
Summary
- Use tuple keys for clear multi-attribute sorting.
- Use numeric negation or stable multi-pass sorting for mixed order direction.
- Prefer
attrgetterfor object and dataclass attributes. - Define missing-value behavior explicitly in sort keys.
- Keep key functions cheap when sorting large lists.

