Using the key Parameter for Custom Sorting
Think of each tuple position as a sorting criterion with a priority.
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 Decision
When items are represented as tuples, their order is decided from left to right. The sort function begins with the first element of each tuple. It considers later elements only when the earlier elements are tied. This gives tuple sorting a predictable, lexicographic ordering.
What do you think happens?
Which tuple comes first when comparing ('Alice', 90) and ('Bob', 85)?
Reveal answer
('Alice', 90)
The first elements are different, so the comparison is decided at the first position. The score is not consulted because there is no tie in the names.
Reading Tuple Positions
Think of each tuple position as a sorting criterion with a priority. The first position has the highest priority because it is checked first. The second position matters only if the first positions match. The third position matters only if both the first and second positions match. This process continues through the tuple until a difference determines the order.
A Difference at the First Position
Compare ('Alice', 90, 2) with ('Bob', 85, 1).
- 1Check the first elements
The first tuple begins with Alice and the second begins with Bob.
- 2Stop at the first difference
Because the first elements differ, the comparison is decided at that position. The scores and years do not resolve this comparison.
The tuple beginning with Alice comes before the tuple beginning with Bob.
Resolving Ties
A tie at one position does not end the comparison. Instead, sorting advances to the next position. For student records written as name, score, and year, names are compared first. If two names match, scores are compared. If both names and scores match, years are compared. The order of the tuple fields therefore determines which criterion receives priority.
Two Equal Names
Compare ('Alice', 90, 2) with ('Alice', 85, 1).
- 1Compare the names
Both tuples have Alice in the first position, so the first comparison is tied.
- 2Move to the scores
The scores are 90 and 85. The comparison is decided at the second position.
- 3Ignore the year for this pair
Because the scores differ, the third position is not needed to determine the order.
The tuple with score 85 is ordered before the tuple with score 90 when the comparison is increasing.
Increasing and Decreasing Order
The reverse=True keyword argument reverses the entire comparison logic. With tuple records, this means the ordering is decreasing at every level: later names come first, and within a matching name group, higher scores come first. The reversal applies to the complete tuple comparison rather than only to one selected position.
| Sorting direction | First position | Tie-breaking positions |
|---|---|---|
| Increasing | Earlier values come first | Later positions are compared in increasing order |
| Decreasing with reverse=True | Later values come first | Later positions are compared in decreasing order |
The direction applies throughout the tuple comparison.
The source describes student records and gives a decreasing-order result: ('Charlie', 85), ('Bob', 90), ('Alice', 90), ('Alice', 85). Charlie comes before Bob and Alice because the names are later in the alphabet. Within the Alice group, the score 90 comes before 85 because the comparison is decreasing.
Predicting the Final Order
To predict a sorted sequence, inspect pairs of tuples from left to right. First group your attention around the first element, because it has the highest priority. Within a group sharing that first element, compare the second element. Continue to the third element only when the earlier positions remain tied. This method follows the same decision process used by tuple comparison.
Predict the decreasing-order arrangement of these records: ('Alice', 85), ('Charlie', 85), ('Bob', 90), ('Alice', 90). Explain which position decides each important comparison.
Hints
- Compare the names before comparing the scores.
- The two Alice records are tied at the first position.
- Because the order is decreasing, compare the Alice scores from higher to lower.
Common Sorting Mistakes
Common mistake Assuming the second element always controls the order
What it looks likeComparing ('Alice', 90) with ('Bob', 85) by looking at 90 and 85 first
Why it failsThe first elements differ, so the comparison is decided before the scores are considered.
Do this insteadAlways begin with the first tuple position and move right only after a tie.
Common mistake Stopping when the first elements tie
What it looks likeTreating ('Alice', 90) and ('Alice', 85) as fully equal
Why it failsA tie in one position means the next position must be checked.
Do this insteadContinue to the second element, then to later elements if necessary.
Common mistake Reversing only the first criterion
What it looks likeExpecting reverse=True to place later names first but keep lower scores first within a name group
Why it failsThe source describes reverse=True as reversing the entire comparison logic.
Do this insteadApply decreasing-order reasoning to every tuple position.
Common mistake Putting the most important criterion later
What it looks likeDesigning a tuple so that the criterion that matters most appears after a less important criterion
Why it failsEarlier positions receive priority during comparison.
Do this insteadPlace the most important criterion in the first position.
Key Takeaways
- 1Tuple sorting checks elements from the first position toward later positions.
- 2A later element is used only when all earlier compared elements are tied.
- 3The first tuple position represents the highest-priority sorting criterion.
- 4reverse=True reverses the ordering at every tuple position.
- 5Predict the result by tracing the first position first, then following tie-breaks to the right.
At a glance
- Sorting tuples uses a left-to-right, element-by-element comparison.
- Ties are resolved by comparing the next tuple element.
- Tuple design determines which sorting criteria receive priority.
- reverse=True produces decreasing order throughout the comparison.
- A reliable prediction strategy is to identify the first differing position for each pair.