Sorting Lists with the sort() Method
Tuple comparison proceeds element by element from left to right, stopping as soon as a difference is found.
The First Difference Decides
A tuple can carry several sorting criteria in a fixed order. Python compares the first elements of two tuples first. If those elements differ, that difference determines the ordering. Python does not need to use later elements. It examines the next element only when the earlier elements are equal.
A Comparison Trace
What do you think happens?
Which tuple comes first when Python compares (2, 9, 4) with (5, 1, 8)?
Reveal answer
Answer: (2, 9, 4)
The first elements differ: 2 is less than 5. That first difference decides the comparison, so the later elements are not needed.
Comparing Two Candidate Keys
Determine the order of (3, 7) and (3, 2).
Compare the first elements: Both first elements are 3, so the first position does not decide the ordering.
Move to the next position: Compare 7 with 2. Because 2 is less than 7, (3, 2) comes before (3, 7).
Stop at the first difference: The second elements differ, so there is no need to inspect any later position.
(3, 2) comes before (3, 7).
This comparison rule gives a sorted list a predictable priority structure. The first tuple element is the primary criterion. The second element is a tie-breaker used only when the primary criteria match. Additional elements continue the same pattern.
Tuple Keys for Multiple Criteria
To sort records by more than one attribute, represent each record with a tuple of sort keys. Put the most important criterion first, followed by the tie-breaking criteria. Sorting then applies the tuple comparison rule: compare the primary key first, and consult the next key only when the earlier key is equal.
Sorting by Priority and Name
Three items have sort keys: Alpha has (1, 8), Beta has (1, 3), and Gamma has (2, 1). Predict their order when the tuple keys are sorted.
Compare the primary values: Alpha and Beta both have primary value 1. Gamma has primary value 2, so both Alpha and Beta come before Gamma.
Break the tie: Alpha and Beta have equal primary values, so compare their second values: 3 comes before 8.
Assemble the result: The tuple keys therefore appear in the order (1, 3), (1, 8), and (2, 1).
Beta, Alpha, Gamma
The position of a value inside the tuple expresses its sorting priority. Moving a criterion earlier makes it more influential because it can decide the comparison before later criteria are considered.
Reading a Sorted Result
When predicting a sorted result, do not compare all tuple elements at once. For each pair, begin at the leftmost position. If the values differ, record the ordering immediately. If they match, move right and repeat. This prevents a later, smaller value from incorrectly overriding an earlier difference.
A Three-Item Trace
Order the keys (2, 5), (1, 9), and (2, 1).
Place the key beginning with 1: The first element 1 is less than 2, so (1, 9) comes before both keys beginning with 2.
Compare the tied primary values: The remaining keys both begin with 2, so compare their second elements: 1 is less than 5.
Write the complete order: The keys are ordered as (1, 9), (2, 1), and (2, 5).
(1, 9), (2, 1), (2, 5)
The DSU Sorting Pipeline
The Decorate-Sort-Undecorate pattern, abbreviated DSU, uses tuples to sort original values by derived criteria. First, decorate each original value by pairing it with one or more sort keys. Next, sort the decorated tuples. Finally, undecorate the result by extracting the original values from the sorted tuples.
Tracing a Derived Sort Key
Sort the original values Cedar, Oak, and Ash by their name lengths using the DSU pattern.
Decorate: Pair each value with its derived key: Cedar becomes (5, Cedar), Oak becomes (3, Oak), and Ash becomes (3, Ash).
Sort: Compare the tuple keys from left to right. The tuples beginning with 3 come before the tuple beginning with 5. Between (3, Oak) and (3, Ash), the first elements tie, so the second elements decide their order.
Undecorate: After the decorated tuples have been ordered, remove the derived keys and keep the original values.
Ash, Oak, Cedar
DSU separates the work into three understandable stages: create comparison-friendly tuples, sort those tuples, and recover the original values. The tuple comparison rule controls the middle stage.
Reverse Ordering Choices
The reverse=True option reverses the comparison for all elements in a tuple. Therefore, it affects both the primary criterion and the tie-breaking criteria. It is not a way to reverse only one selected position in a multi-criteria tuple.
| Approach | Effect on tuple criteria | Best interpretation |
|---|---|---|
| Tuple sort key | Earlier elements have priority; later elements break ties | Use for ordered multi-criteria keys |
| reverse=True | Reverses comparison for all tuple elements | Use when every tuple criterion should reverse together |
| Custom key function | Provides finer-grained control over multi-criteria sorting | Use when criteria require different ordering directions |
Mistakes in Tuple Sorting
Looking at the second tuple element before checking the first
The first elements differ, and 1 is less than 2. That first difference decides the ordering.
Fix:
Compare tuple positions from left to right and stop when the first difference appears.Using a later criterion as if it were the primary criterion
Tuple position determines priority.
Fix:
Place the most important sort key first and use later positions for tie-breaking.Assuming reverse=True reverses only the primary criterion
reverse=True reverses the comparison for all elements in the tuple.
Fix:
Use a custom key function when different criteria need different directions.Skipping the undecorate stage in DSU
DSU uses tuples during sorting but extracts the original values afterward.
Fix:
After sorting, remove the derived sort keys and retain the original values.
Check Your Reasoning
A collection has these tuple keys: (4, 2), (2, 9), (4, 1), and (2, 3). Predict the sorted order. Then identify which comparisons require the second element.
Hints
- Group the keys by their first element.
- Within each group sharing a first element, compare the second elements.
- The second element is needed only when the first elements are equal.
Design a DSU trace for the original values Pine, Elm, and Birch, using string length as the derived key. Show the decorated tuples, their sorted order, and the final undecorated order.
Hints
- Create one tuple containing the derived length and the original value for each item.
- Compare the tuples from left to right.
- Extract the original value after the decorated tuples are ordered.
Key Takeaways
- Python compares tuples from left to right and stops at the first difference.
- The first tuple element is the primary sort criterion; later elements break ties.
- Tuple keys support multi-criteria sorting by placing criteria in priority order.
- DSU decorates original values with sort keys, sorts the tuples, and then extracts the original values.
- reverse=True reverses every tuple comparison criterion, so a custom key function is preferable for fine-grained control.
Key Takeaways
- Tuple comparison proceeds left to right and stops at the first differing element.
- A tuple sort key expresses primary, secondary, and later sorting priorities by position.
- When earlier tuple elements match, Python uses the next element as a tie-breaker.
- The DSU pattern sorts derived keys while preserving a path back to the original values.
- reverse=True reverses all tuple criteria; use a custom key function for more selective control.