Sorting Lists with the sort() Method
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.
Try it: Sorting with key= and reverse=
How sorted() and list.sort() compute key(item) once per item, order the items by those keys with Python's comparison rules, and keep equal keys in their original order — including py4e's sort-a-dict-by-value pattern.
How it works
- Decorate: call the key function once on every item (no key means the item itself is compared).
- Compare keys with Python's rules: ints by value, strs by code point ('Z' < 'a'), tuples item by item.
- Order the items by key; reverse=True puts the largest key first.
- Stable: items with equal keys keep their original relative order, also with reverse=True.
- sorted() returns a new list; list.sort() rearranges the list in place and returns None; [:N] keeps the first N.
Default run (12 steps): 5 items in their original order. Python will call lambda t: t[1] once per item. … sorted() returned a new list: result = [('fig', 5), ('kiwi', 5), ('pear', 3), ('apple', 3), ('date', 1)].
Simplified: Up to 10 items of one kind (ints, short ASCII words, (word, count) tuples or a small dict) and a fixed menu of key functions. The sorting algorithm itself (Timsort) is not shown — only what it guarantees: the order by key and stability.
Loading the simulation…
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
(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).
- 1Compare the first elements
Both first elements are 3, so the first position does not decide the ordering.
- 2Move to the next position
Compare 7 with 2. Because 2 is less than 7, (3, 2) comes before (3, 7).
- 3Stop 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.
- 1Compare the primary values
Alpha and Beta both have primary value 1. Gamma has primary value 2, so both Alpha and Beta come before Gamma.
- 2Break the tie
Alpha and Beta have equal primary values, so compare their second values: 3 comes before 8.
- 3Assemble 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).
- 1Place the key beginning with 1
The first element 1 is less than 2, so (1, 9) comes before both keys beginning with 2.
- 2Compare the tied primary values
The remaining keys both begin with 2, so compare their second elements: 1 is less than 5.
- 3Write 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.
- 1Decorate
Pair each value with its derived key: Cedar becomes (5, Cedar), Oak becomes (3, Oak), and Ash becomes (3, Ash).
- 2Sort
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.
- 3Undecorate
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 |
How tuple keys and reverse ordering differ
Mistakes in Tuple Sorting
Common mistake Looking at the second tuple element before checking the first
What it looks likeTreating (1, 9) as greater than (2, 0) because 9 is greater than 0
Why it failsThe first elements differ, and 1 is less than 2. That first difference decides the ordering.
Do this insteadCompare tuple positions from left to right and stop when the first difference appears.
Common mistake Using a later criterion as if it were the primary criterion
What it looks likeTrying to order records by the second value even though the first value was intended to be the main grouping
Why it failsTuple position determines priority.
Do this insteadPlace the most important sort key first and use later positions for tie-breaking.
Common mistake Assuming reverse=True reverses only the primary criterion
What it looks likeExpecting the first tuple element to reverse while the second element keeps its original direction
Why it failsreverse=True reverses the comparison for all elements in the tuple.
Do this insteadUse a custom key function when different criteria need different directions.
Common mistake Skipping the undecorate stage in DSU
What it looks likeReturning the sorted tuples when the desired result is the original values
Why it failsDSU uses tuples during sorting but extracts the original values afterward.
Do this insteadAfter 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
- 1Python compares tuples from left to right and stops at the first difference.
- 2The first tuple element is the primary sort criterion; later elements break ties.
- 3Tuple keys support multi-criteria sorting by placing criteria in priority order.
- 4DSU decorates original values with sort keys, sorts the tuples, and then extracts the original values.
- 5reverse=True reverses every tuple comparison criterion, so a custom key function is preferable for fine-grained control.
At a glance
- 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.