Custom Sorting with Lambda Functions
The position of a value inside the tuple matters. A value in the first position is considered before a value in the second position, so changing the tuple from (score, name) to (name, score) changes the sorting priorities.
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…
A Sort Key Can Contain Several Decisions
A sorting operation becomes more useful when each item must be judged by more than one attribute. For example, records might first be ordered by score and then by name when scores are equal. Python can represent those decisions as a tuple. The first tuple element supplies the primary comparison, and later elements supply tie-breakers.
What do you think happens?
Suppose Python compares the sort keys (80, "Mira") and (75, "Noah"). Which key comes first?
Reveal answer
(75, "Noah")
Tuple comparison begins with the first element. Because 80 and 75 differ, the comparison stops there. The names are not needed to decide this pair.
Reading Tuple Comparisons
Tuple comparison proceeds element by element from left to right. Python checks the first elements. If they differ, that difference determines the ordering and the remaining elements do not affect that comparison. If the first elements are equal, Python continues to the next elements. This continues until a difference is found.
Finding the Tie-Breaker
Compare the keys (72, "Zoe") and (72, "Ari"). Which key comes first in ordinary ascending order?
- 1Compare the primary values
The first elements are both 72, so the first comparison does not decide the order.
- 2Move to the next element
Python compares the second elements, Zoe and Ari.
- 3Use the first difference
The second elements differ, so that difference determines the order.
(72, "Ari") comes before (72, "Zoe") because the second elements break the tie.
The position of a value inside the tuple matters. A value in the first position is considered before a value in the second position, so changing the tuple from (score, name) to (name, score) changes the sorting priorities.
Building Multi-Criteria Keys
A lambda function can produce the tuple used as a sort key. For a record with a score and a name, a key function conceptually produces (record score, record name). Sorting by those generated tuples orders records by score first. Only records with equal scores reach the name comparison.
Sorting by Score, Then Name
Order these records using tuple keys containing score first and name second: Mira with 80, Zoe with 72, Ari with 72, and Leo with 80.
- 1Create the keys
The records become (80, Mira), (72, Zoe), (72, Ari), and (80, Leo).
- 2Compare the first elements
The records with score 72 come before the records with score 80 in ascending order.
- 3Break the first tie
Among the score-72 records, Ari and Zoe are compared by their second elements.
- 4Break the second tie
Among the score-80 records, Leo and Mira are compared by their second elements.
Ari, Zoe, Leo, Mira
Tracing the DSU Pattern
The Decorate-Sort-Undecorate pattern explains sorting by a derived value in three stages. First, decorate each original item by creating a tuple that places the desired sort key alongside the original value. Second, sort those tuples. Because tuple comparison examines the key elements first, the derived values control the order. Third, undecorate by extracting the original values and removing the temporary keys.
Following One Record Through DSU
Trace the record Mira with score 80 through a DSU process where the score is the derived sort key.
- 1Original value
The item begins as Mira with an associated score of 80.
- 2Decorate
A tuple such as (80, Mira) stores the sort key together with the original value.
- 3Sort
The decorated tuples are compared. The first element, 80, participates in the primary ordering.
- 4Undecorate
After sorting, the temporary key is removed by extracting Mira from the tuple.
The final output contains the original value Mira in the position determined by its derived tuple key.
Choosing Ascending and Descending Criteria
reverse=True reverses the comparison for all elements in a tuple. Therefore, when a tuple contains a primary criterion and a tie-breaking criterion, reverse=True affects both of them. It does not independently choose a different direction for each tuple position.
| Approach | Effect | Use when |
|---|---|---|
| Tuple key | Places several criteria in a left-to-right comparison order | The criteria follow the same comparison direction |
| reverse=True | Reverses comparison for every element in the tuple | All tuple criteria should be reversed together |
| Custom key function | Provides finer-grained control over multi-criteria sorting | Different criteria need different ordering decisions |
The source distinguishes whole-tuple reversal from fine-grained control through a custom key function.
Mistakes in Multi-Criteria Sorting
Common mistake Comparing the second tuple element before the first
What it looks likeTreating (80, "Mira") as if the name controlled the order before the score
Why it failsTuple comparison proceeds from left to right, so the first element has priority.
Do this insteadRead the tuple positions in order and identify the first position where the two keys differ.
Common mistake Using a tie-breaker when the primary values already differ
What it looks likeComparing Ari and Zoe even though their scores are 72 and 80
Why it failsOnce a difference is found, later tuple elements do not affect that comparison.
Do this insteadStop the trace at the first difference.
Common mistake Assuming reverse=True changes only the primary criterion
What it looks likeExpecting the score direction to reverse while the name tie-breaker keeps its original direction
Why it failsreverse=True reverses comparison for all elements in the tuple.
Do this insteadUse a custom key function when different criteria require finer-grained control.
Common mistake Forgetting to remove the temporary decoration
What it looks likeReturning tuples such as (72, "Ari") when the desired result is the original record
Why it failsThe DSU pattern uses the tuple during sorting and then extracts the original values.
Do this insteadUndecorate after sorting by extracting the original values.
Practice the Trace
A collection contains these records: Nia with priority 3, Omar with priority 1, Bea with priority 3, and Kai with priority 2. A lambda-generated tuple key places priority first and name second. Predict the final ascending order. Write the generated tuple for each record, group records by their first element, and then compare names only within equal-priority groups.
Hints
- The priority is the first tuple element.
- The names are compared only when two priorities are equal.
- The tuple keys are (3, Nia), (1, Omar), (3, Bea), and (2, Kai).
Checking the Practice Result
Use the tuple keys (3, Nia), (1, Omar), (3, Bea), and (2, Kai) to determine the ascending order.
- 1Order by the first elements
Priority 1 comes before priority 2, and priority 2 comes before priority 3.
- 2Resolve the priority-3 tie
Nia and Bea have equal first elements, so compare their second elements.
- 3Read the original values
After the tuple keys are ordered, extract the associated names.
Omar, Kai, Bea, Nia
Key Takeaways
- 1Python compares tuple elements from left to right and stops at the first difference.
- 2The first tuple element is the primary sort criterion; later elements break ties.
- 3A lambda key function can produce tuples that express multi-criteria ordering.
- 4The DSU pattern decorates original values with sort keys, sorts the decorated tuples, and then extracts the original values.
- 5reverse=True reverses every comparison in a tuple, while a custom key function gives finer-grained control.
At a glance
- Tuple comparison is a left-to-right process controlled by the first difference.
- Tuple sort keys naturally express primary criteria and tie-breakers.
- Lambda functions can generate those keys for each item.
- DSU makes derived-value sorting understandable as decoration, sorting, and undecoration.
- Use a custom key function when reversing every tuple criterion together is not the desired behavior.