Custom Sorting with Lambda Functions
Tuple comparison proceeds element by element from left to right, stopping as soon as a difference is found.
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
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?
Compare the primary values: The first elements are both 72, so the first comparison does not decide the order.
Move to the next element: Python compares the second elements, Zoe and Ari.
Use 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.
Create the keys: The records become (80, Mira), (72, Zoe), (72, Ari), and (80, Leo).
Compare the first elements: The records with score 72 come before the records with score 80 in ascending order.
Break the first tie: Among the score-72 records, Ari and Zoe are compared by their second elements.
Break 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.
Original value: The item begins as Mira with an associated score of 80.
Decorate: A tuple such as (80, Mira) stores the sort key together with the original value.
Sort: The decorated tuples are compared. The first element, 80, participates in the primary ordering.
Undecorate: 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 |
Mistakes in Multi-Criteria Sorting
Comparing the second tuple element before the first
Tuple comparison proceeds from left to right, so the first element has priority.
Fix:
Read the tuple positions in order and identify the first position where the two keys differ.Using a tie-breaker when the primary values already differ
Once a difference is found, later tuple elements do not affect that comparison.
Fix:
Stop the trace at the first difference.Assuming reverse=True changes only the primary criterion
reverse=True reverses comparison for all elements in the tuple.
Fix:
Use a custom key function when different criteria require finer-grained control.Forgetting to remove the temporary decoration
The DSU pattern uses the tuple during sorting and then extracts the original values.
Fix:
Undecorate 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.
Order by the first elements: Priority 1 comes before priority 2, and priority 2 comes before priority 3.
Resolve the priority-3 tie: Nia and Bea have equal first elements, so compare their second elements.
Read the original values: After the tuple keys are ordered, extract the associated names.
Omar, Kai, Bea, Nia
Key Takeaways
- Python compares tuple elements from left to right and stops at the first difference.
- The first tuple element is the primary sort criterion; later elements break ties.
- A lambda key function can produce tuples that express multi-criteria ordering.
- The DSU pattern decorates original values with sort keys, sorts the decorated tuples, and then extracts the original values.
- reverse=True reverses every comparison in a tuple, while a custom key function gives finer-grained control.
Key Takeaways
- 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.