Concepts / Sorting and the key Parameter

Sorting and the key Parameter

A lambda statement creates an anonymous function object with one parameter and one expression.

  • 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 Sorting Question

Suppose a sorting operation needs a special value from each item before it can compare the items. Python's key parameter accepts a function that determines that value. A lambda is useful here because it creates a small, anonymous function inline instead of requiring a separately named function.

lambda x: x * 2 + 1anonymous function objectkeyreceives the functionsort()calls the functioncomparison valuesvalues used for comparisonpassed asavailable toproduces
How does a lambda become a function object and reach the sorting operation through the key parameter?

Lambda Anatomy

Definition

A lambda statement creates an anonymous function object with one parameter and one expression. Anonymous means that the function is created without a regular function name.

lambdastarts the lambdaxparameter:separatorx * 2 + 1single expression andreturn value
What does each part of a lambda represent?
Pattern
lambda parameter : expression

The keyword lambda begins the structure. The parameter is the name that receives an argument when the function is called. The colon separates the parameter from the expression. The expression is the entire function body, so it is also the value returned by the lambda. There is no separate multi-line body to execute.

Tracing Each Key

When a sorting operation uses a lambda as its key function, the operation can call that lambda for each item. To trace one call, start with the item as the argument, bind that value to the lambda parameter, substitute the value into the expression, and evaluate the result. The resulting value is the key used for comparison.

4argumentx = 4parameter binding4 * 2 + 1substitution9returned keybecomesused inevaluates to
What happens when the lambda receives an item, evaluates its expression, and returns a key?
Worked example

Tracing a Sorting Key

Consider sorting the values 4, 1, and 3 with the generated key lambda x: x * 2 + 1.

  1. 1
    Process 4

    Bind 4 to x. Substitute it into the expression: 4 * 2 + 1. The key is 9.

  2. 2
    Process 1

    Bind 1 to x. Substitute it into the expression: 1 * 2 + 1. The key is 3.

  3. 3
    Process 3

    Bind 3 to x. Substitute it into the expression: 3 * 2 + 1. The key is 7.

  4. 4
    Compare the keys

    The original values have keys 9, 3, and 7. Sorting uses these key values for comparison.

Result

The final sorted order is 1, 3, 4 because their key values are ordered as 3, 7, 9.

ItemSubstitutionKey
44 * 2 + 19
11 * 2 + 13
33 * 2 + 17

Each item is passed to the same lambda, but each call produces a key from that item's value.

Lambda or def

LambdaRegular function with def
Anonymous and inlineHas a name
Limited to one expressionCan span multiple lines
Useful for a simple, one-time functionUseful for reusable functions
Convenient when passed directly to sort() as keyClearer for complex logic or multiple statements

Both forms create callable function objects; their syntax, scope of use, and suitable situations differ.

A lambda and a regular function defined with def serve the same broad purpose: both create callable function objects. The practical choice depends on the function's role. Use lambda when the operation is short, simple, and needed only once, such as an inline key function for sorting. Use def when the function should have a name, be reused, contain multiple statements, or express more complex logic clearly.

In the real world

A sorting operation often needs a small rule that is useful only during that operation. Supplying a lambda directly as the key avoids creating a separately named function for a one-time transformation.

Mistakes in Lambda Tracing

  • Common mistake

    Treating the expression after the colon as only part of the function body.

    What it looks like
    lambda x: x * 2 + 1
    Why it fails

    The expression is the entire function body and the value returned by the lambda.

    Do this instead

    Read the expression as the complete operation performed for each call.

  • Common mistake

    Skipping the parameter binding step.

    What it looks like

    For an argument of 4, evaluating x * 2 + 1 without replacing x.

    Why it fails

    The expression must be evaluated with the argument's value bound to the parameter.

    Do this instead

    Write x = 4, substitute 4 into the expression, and then evaluate.

  • Common mistake

    Assuming the lambda is evaluated only once when used as a sorting key.

    What it looks like

    Creating one key for the whole collection.

    Why it fails

    The sorting operation uses the key function for the items being considered, with different argument values.

    Do this instead

    Trace the lambda separately for each item and record each returned key.

  • Common mistake

    Using lambda for logic that needs multiple statements or repeated reuse.

    What it looks like

    Trying to represent complex logic in one long expression.

    Why it fails

    A lambda is limited to a single expression and is intended for simple, often one-time functions.

    Do this instead

    Define a named regular function with def when the logic is complex or reusable.

Try the Trace

EASY

For the lambda x: x * 3 + 2, trace the call whose argument is 5. Write the parameter binding, the substituted expression, and the returned value. Then decide whether this lambda is a simple one-time operation or a good candidate for a named function.

Hints
  • Begin with x = 5.
  • Replace x in x * 3 + 2 with 5.
  • Evaluate multiplication before addition.

What do you think happens?

What value does lambda x: x * 3 + 2 return when called with 5?

  • 17

  • 25

  • 15

  • 10

Reveal answer
Answer:

17

Bind 5 to x, substitute it into the expression, and evaluate 5 * 3 + 2 as 15 + 2, which is 17.

Key Takeaways

  1. 1
    A lambda statement creates an anonymous function object with a parameter and one expression.
  2. 2
    Its structure is lambda, a parameter, a colon, and a single expression that is evaluated and returned.
  3. 3
    When used as a sorting key, the lambda is called for items so that key values can be used for comparison.
  4. 4
    To trace a lambda, bind the argument to the parameter, substitute it into the expression, and evaluate the result.
  5. 5
    Use lambda for simple one-time functions; use def for named, reusable, multi-line, or complex logic.

At a glance

  • A lambda creates an anonymous callable function object.
  • The parameter receives an argument, and the single expression produces the returned value.
  • The sort key function is applied to items so that the resulting key values determine comparison.
  • Substitution is the most reliable way to trace lambda execution.
  • Choose def when a function needs a name, reuse, multiple statements, or complex logic.

Related concepts

More concepts starting with S