Sorting and the key Parameter
A lambda statement creates an anonymous function object with one parameter and one expression.
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 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 Anatomy
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.
lambda parameter : expressionThe 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.
Tracing a Sorting Key
Consider sorting the values 4, 1, and 3 with the generated key lambda x: x * 2 + 1.
- 1Process 4
Bind 4 to x. Substitute it into the expression: 4 * 2 + 1. The key is 9.
- 2Process 1
Bind 1 to x. Substitute it into the expression: 1 * 2 + 1. The key is 3.
- 3Process 3
Bind 3 to x. Substitute it into the expression: 3 * 2 + 1. The key is 7.
- 4Compare the keys
The original values have keys 9, 3, and 7. Sorting uses these key values for comparison.
The final sorted order is 1, 3, 4 because their key values are ordered as 3, 7, 9.
| Item | Substitution | Key |
|---|---|---|
| 4 | 4 * 2 + 1 | 9 |
| 1 | 1 * 2 + 1 | 3 |
| 3 | 3 * 2 + 1 | 7 |
Each item is passed to the same lambda, but each call produces a key from that item's value.
Lambda or def
| Lambda | Regular function with def |
|---|---|
| Anonymous and inline | Has a name |
| Limited to one expression | Can span multiple lines |
| Useful for a simple, one-time function | Useful for reusable functions |
| Convenient when passed directly to sort() as key | Clearer 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.
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 likelambda x: x * 2 + 1Why it failsThe expression is the entire function body and the value returned by the lambda.
Do this insteadRead the expression as the complete operation performed for each call.
Common mistake Skipping the parameter binding step.
What it looks likeFor an argument of 4, evaluating x * 2 + 1 without replacing x.
Why it failsThe expression must be evaluated with the argument's value bound to the parameter.
Do this insteadWrite 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 likeCreating one key for the whole collection.
Why it failsThe sorting operation uses the key function for the items being considered, with different argument values.
Do this insteadTrace 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 likeTrying to represent complex logic in one long expression.
Why it failsA lambda is limited to a single expression and is intended for simple, often one-time functions.
Do this insteadDefine a named regular function with def when the logic is complex or reusable.
Try the Trace
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?
Reveal answer
17
Bind 5 to x, substitute it into the expression, and evaluate 5 * 3 + 2 as 15 + 2, which is 17.
Key Takeaways
- 1A lambda statement creates an anonymous function object with a parameter and one expression.
- 2Its structure is lambda, a parameter, a colon, and a single expression that is evaluated and returned.
- 3When used as a sorting key, the lambda is called for items so that key values can be used for comparison.
- 4To trace a lambda, bind the argument to the parameter, substitute it into the expression, and evaluate the result.
- 5Use 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.