- 5.1 Function Definitions
- 5.2 Default Arguments
- 5.3 Variadic Arguments
- 5.4 Keyword Arguments
- 5.5 Variadic Keyword Arguments
- 5.6 Functions Accepting All Inputs
- 5.7 Positional-Only Arguments
- 5.8 Names, Documentation Strings, and Type Hints
- 5.9 Function Application and Parameter Passing
- 5.10 Return Values
- 5.11 Error Handling
- 5.12 Scoping Rules
- 5.13 Recursion
- 5.14 The lambda Expression
- 5.15 Higher-Order Functions
- 5.16 Argument Passing in Callback Functions
- 5.17 Returning Results from Callbacks
- 5.18 Decorators
- 5.19 Map, Filter, and Reduce
- 5.20 Function Introspection, Attributes, and Signatures
- 5.21 Environment Inspection
- 5.22 Dynamic Code Execution and Creation
- 5.23 Asynchronous Functions and await
- 5.24 Final Words: Thoughts on Functions and Composition
5.14 The lambda Expression
An anonymous—unnamed—function can be defined with a lambda expression:
lambda args: expression
args is a comma-separated list of arguments, and expression is an expression involving those arguments. Here’s an example:
a = lambda x, y: x + y r = a(2, 3) # r gets 5
The code defined with lambda must be a valid expression. Multiple statements, or nonexpression statements such as try and while, cannot appear in a lambda expression.
One of the main uses of lambda is to define small callback functions. For example, you may see it used with built-in operations such as sorted(). For example:
# Sort a list of words by the number of unique letters result = sorted(words, key=lambda word: len(set(word)))
Caution is required when a lambda expression contains free variables (not specified as parameters). Consider this example:
x = 2 f = lambda y: x * y x = 3 g = lambda y: x * y print(f(10)) # --> prints 30 print(g(10)) # --> prints 30
In this example, you might expect the call f(10) to print 20, reflecting the fact that x was 2 at the time of definition. However, this is not the case. As a free variable, the evaluation of f(10) uses whatever value x happens to have at the time of evaluation. It could be different from the value it had when the lambda function was defined. Sometimes this behavior is referred to as late binding.
If it’s important to capture the value of a variable at the time of definition, use a default argument:
x = 2 f = lambda y, x=x: x * y x = 3 g = lambda y, x=x: x * y print(f(10)) # --> prints 20 print(g(10)) # --> prints 30
This works because default argument values are only evaluated at the time of function definition and thus would capture the current value of x.