Higher-Order Functions
A lambda statement creates an anonymous function object with one parameter and one expression.
Try it: Functions as Values: Lambda
That a lambda (like def) evaluates to a function object that a name can refer to and that can be passed to other functions — apply(f, x), twice(f, x), map(f, xs), sorted(xs, key=f) — and that each call is traced by binding the argument, substituting it into the single expression and evaluating in operator order.
How it works
- lambda x: expression evaluates to a function object (named <lambda>); nothing inside it is computed yet. f = ... gives it a name, exactly as def f(x): return expression would.
- Writing f without parentheses passes the function object itself; inside apply or twice the parameter func refers to the same object.
- A call binds the argument to the parameter x, substitutes it into the expression, and evaluates by operator precedence (* and % before + and -, parentheses first).
- The value of the expression is the call's return value; there is no other body.
- map(f, xs) calls f once per item and keeps the results in order; sorted(xs, key=f) calls f once per item to get keys, orders by the keys (ties keep their order) and returns the items.
Default run (9 steps): The program is ready: a lambda written inline, then f(x). … print shows 7.
Simplified: Four one-parameter lambdas with editable integer constants, small int arguments (at most 6 items). Each substituted expression the lab shows was evaluated by CPython 3.12 and has the same value as the real call; printed results and ZeroDivisionError messages match CPython.
Loading the simulation…
A Function as a Value
A lambda statement creates an anonymous function object with one parameter and one expression. Because the resulting function object can be passed as an argument, a lambda can control how another function performs a computation. This is especially useful when a short function is needed only once, such as the key function supplied to sort().
Tracing a Lambda Call
What do you think happens?
Suppose a lambda has the form lambda x: x * 2 + 1 and is called with 3. What result should it return?
Reveal answer
7
The argument 3 becomes the value of x. Substituting gives 3 * 2 + 1. Multiplication happens before addition, so the result is 6 + 1, which is 7.
Evaluating One Lambda Call
Trace the call of lambda x: x * 2 + 1 with the argument 3.
- 1Bind the argument
The argument 3 becomes the value of the parameter x.
- 2Substitute
Replace x in the expression with 3, producing 3 * 2 + 1.
- 3Follow operation order
Evaluate multiplication before addition: 3 * 2 is 6, then add 1.
- 4Return the expression result
The expression is the entire function body, so its result is returned immediately.
7
A reliable tracing method is always the same: start with the argument, bind it to the parameter, substitute the parameter into the expression, and evaluate the expression in its normal order of operations. A lambda has no separate sequence of statements to execute. Its single expression is the entire function and its return value.
Lambda Syntax
The basic pattern is lambda parameter : expression. The keyword lambda begins the statement, the parameter names the input, the colon separates the parameter from the expression, and the expression is evaluated and returned whenever the lambda is called.
The expression does not merely describe what the lambda should do later; it is the whole function body. When the lambda is called, the expression is evaluated using the argument supplied for the parameter, and the resulting value is returned.
Passing Functions to sort()
A practical use of a lambda is providing the key parameter to sort(). The key parameter tells sort() which value to use for comparison. A lambda can be written inline when the comparison rule is short and is not needed elsewhere.
items.sort(key=lambda item: item * 2)- 1The lambda creates an anonymous function object.
- 2The function object is passed to
sort()through the key parameter. - 3
sort()can call the key function while determining comparison values. - 4For each call, the current item becomes the value of item, and item * 2 is evaluated.
items.sort()performs the sorting operation.- key receives a function object.
- lambda item: item * 2 defines the short key computation.
- The parameter item is replaced by an item value when the lambda is called.
Lambda or def
| Lambda | Regular function with def |
|---|---|
| Anonymous | Has a name |
| Written inline | Defined separately |
| Limited to one expression | Can span multiple lines |
| Useful for a simple, one-time function | Useful for reusable functions and complex logic |
Both forms create callable function objects, but their structure and typical use cases differ.
Use a lambda when the operation is simple, short, and often passed directly as an argument. Use def when the function should have a name, be reused, contain multiple statements, or express complex logic. The choice is not about whether either form can create a callable function object; both can. The choice is about clarity, scope, and use case.
Mistakes in Lambda Tracing
Common mistake Treating the colon as the return value
What it looks likelambda x: x * 2Why it failsThe colon separates the parameter from the expression. The expression after the colon is the body and return value.
Do this insteadRead the pattern as keyword, parameter, colon, then one expression.
Common mistake Forgetting to substitute the argument
What it looks likeCalling lambda x: x * 2 with 4
Why it failsThe parameter x receives the argument value before the expression is evaluated.
Do this insteadWrite the substitution explicitly: 4 * 2.
Common mistake Ignoring operation order
What it looks likeReading x * 2 + 1 as x * (2 + 1)Why it failsMultiplication happens before addition, so these expressions do not produce the same result.
Do this insteadEvaluate the substituted expression using its normal order of operations.
Common mistake Using a lambda for complex or reusable logic
What it looks likeWriting a long computation as one inline expression
Why it failsA lambda is intended for a simple, one-time function and is limited to a single expression.
Do this insteadUse a named def function when the logic is complex or needs to be reused.
Practice the Substitution Method
Trace lambda number: number * 3 + 2 when it is called with 4. Write the parameter binding, the substituted expression, and the final result.
Hints
- First bind number to 4.
- Then replace number in the expression.
- Evaluate multiplication before addition.
Decide whether a lambda or a named def function is clearer for a reusable operation that contains multiple statements. Explain your choice using the differences in naming, length, and complexity.
Hints
- Consider whether the function is reusable.
- Consider whether one expression is enough.
- A named function can span multiple lines and contain complex logic.
Key Takeaways
- 1A lambda statement creates an anonymous function object.
- 2Its structure is lambda, one parameter, a colon, and one expression.
- 3The expression is the entire function body and is returned when the lambda is called.
- 4To trace a lambda, bind the argument to the parameter, substitute it into the expression, and evaluate the result in order.
- 5Use lambda for simple, one-time functions passed as arguments; use def for named, reusable, or complex logic.
At a glance
- A lambda creates an anonymous callable function object.
- The parameter receives the argument, and the single expression is evaluated and returned.
- Lambda is especially useful for short functions passed to operations such as
sort(). - A regular def function is clearer when logic is complex, spans multiple statements, or must be reused.
- Substitution and normal operation order provide a dependable way to predict lambda results.