Concepts / Custom Sorting with Lambda Functions

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.

  • Programming
Interactive lab

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

  1. Decorate: call the key function once on every item (no key means the item itself is compared).
  2. Compare keys with Python's rules: ints by value, strs by code point ('Z' < 'a'), tuples item by item.
  3. Order the items by key; reverse=True puts the largest key first.
  4. Stable: items with equal keys keep their original relative order, also with reverse=True.
  5. 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.

Educational simulation

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?

  • (80, "Mira")

  • (75, "Noah")

  • The result cannot be determined until the names are compared

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.

(80, Mira)sort key80first elementMiranot reached(75, Noah)sort key75first elementNoahnot reachedinspect firstinspect first80 versus 75not compared
Which elements does Python inspect, and where does the comparison stop?

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.

Worked example

Finding the Tie-Breaker

Compare the keys (72, "Zoe") and (72, "Ari"). Which key comes first in ordinary ascending order?

  1. 1
    Compare the primary values

    The first elements are both 72, so the first comparison does not decide the order.

  2. 2
    Move to the next element

    Python compares the second elements, Zoe and Ari.

  3. 3
    Use the first difference

    The second elements differ, so that difference determines the order.

Result

(72, "Ari") comes before (72, "Zoe") because the second elements break the tie.

Zoescore 72(72, Zoe)tuple key72primary attributeZoetie-breakerbecomesposition 1position 2
How does each position in a tuple sort key contribute to the ordering?
Key point

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.

Mirascore 80(80, Mira)generated keyAri before Mirakey orderAriscore 72(72, Ari)generated keylambda produceslambda producescompare keyscompare keys
What key value does the lambda produce for each item, and how does that value guide its position?
Worked example

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.

  1. 1
    Create the keys

    The records become (80, Mira), (72, Zoe), (72, Ari), and (80, Leo).

  2. 2
    Compare the first elements

    The records with score 72 come before the records with score 80 in ascending order.

  3. 3
    Break the first tie

    Among the score-72 records, Ari and Zoe are compared by their second elements.

  4. 4
    Break the second tie

    Among the score-80 records, Leo and Mira are compared by their second elements.

Result

Ari, Zoe, Leo, Mira

Mira80Ari72Zoe72Zoe72Ari72Leo80Leo80Mira80sorted by keysorted by keysorted by keysorted by key
Given equal primary attributes and different secondary attributes, what final order does tuple sorting produce?

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.

Mirascore 80(80, Mira)key plus value(80, Mira)sorted tupleMiraoriginal valuedecoratesort tuplesextract value
How does an original item move through a derived key, sorting, and removal of the temporary key?
Worked example

Following One Record Through DSU

Trace the record Mira with score 80 through a DSU process where the score is the derived sort key.

  1. 1
    Original value

    The item begins as Mira with an associated score of 80.

  2. 2
    Decorate

    A tuple such as (80, Mira) stores the sort key together with the original value.

  3. 3
    Sort

    The decorated tuples are compared. The first element, 80, participates in the primary ordering.

  4. 4
    Undecorate

    After sorting, the temporary key is removed by extracting Mira from the tuple.

Result

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.

ApproachEffectUse when
Tuple keyPlaces several criteria in a left-to-right comparison orderThe criteria follow the same comparison direction
reverse=TrueReverses comparison for every element in the tupleAll tuple criteria should be reversed together
Custom key functionProvides finer-grained control over multi-criteria sortingDifferent 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 like

    Treating (80, "Mira") as if the name controlled the order before the score

    Why it fails

    Tuple comparison proceeds from left to right, so the first element has priority.

    Do this instead

    Read 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 like

    Comparing Ari and Zoe even though their scores are 72 and 80

    Why it fails

    Once a difference is found, later tuple elements do not affect that comparison.

    Do this instead

    Stop the trace at the first difference.

  • Common mistake

    Assuming reverse=True changes only the primary criterion

    What it looks like

    Expecting the score direction to reverse while the name tie-breaker keeps its original direction

    Why it fails

    reverse=True reverses comparison for all elements in the tuple.

    Do this instead

    Use a custom key function when different criteria require finer-grained control.

  • Common mistake

    Forgetting to remove the temporary decoration

    What it looks like

    Returning tuples such as (72, "Ari") when the desired result is the original record

    Why it fails

    The DSU pattern uses the tuple during sorting and then extracts the original values.

    Do this instead

    Undecorate after sorting by extracting the original values.

Practice the Trace

MEDIUM

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).
Worked example

Checking the Practice Result

Use the tuple keys (3, Nia), (1, Omar), (3, Bea), and (2, Kai) to determine the ascending order.

  1. 1
    Order by the first elements

    Priority 1 comes before priority 2, and priority 2 comes before priority 3.

  2. 2
    Resolve the priority-3 tie

    Nia and Bea have equal first elements, so compare their second elements.

  3. 3
    Read the original values

    After the tuple keys are ordered, extract the associated names.

Result

Omar, Kai, Bea, Nia

Key Takeaways

  1. 1
    Python compares tuple elements from left to right and stops at the first difference.
  2. 2
    The first tuple element is the primary sort criterion; later elements break ties.
  3. 3
    A lambda key function can produce tuples that express multi-criteria ordering.
  4. 4
    The DSU pattern decorates original values with sort keys, sorts the decorated tuples, and then extracts the original values.
  5. 5
    reverse=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.

Related concepts

More concepts starting with C