Python Reference ยท Statements and Keywords
The lambda expression
Reference for Python's lambda expression: syntax, use as key functions with sorted, map and filter, default arguments, late binding and when to prefer def.
lambda creates a small anonymous function as an expression. Its body is a single expression whose value is returned automatically; it cannot contain statements such as return, assignments (other than :=), for loops or try.
Lambdas are mostly written inline as arguments: a key= function for sorted(), min() or max(), a callback, or a tiny adapter. When a function needs a name, documentation, several lines or annotations, use def.
square = lambda x: x * x square(4) # 16
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.
Syntax
lambda parameters: expression
| Part | Description |
|---|---|
parameters |
Same forms as def: defaults, *args, **kwargs, keyword-only and positional-only parameters. No annotations. |
expression |
One expression. Its value is the return value. |
Return value: a function object. Calling it returns the expression's value.
Usage notes
- Single expression only. For logic, use
x if cond else y,and/or, or write adef. Parentheses are needed to return a tuple:lambda: (1, 2). - Late binding. A lambda looks up outer variables when it is called, not when it was created. In loops, bind the current value with a default (
lambda i=i: i) or usefunctools.partial. - No name. Tracebacks and
__name__show<lambda>, which makes debugging harder. Do not assign a lambda to a name just to call it later (PEP 8 recommendsdefinstead). - No annotations or docstring in the lambda itself.
- Precedence.
lambdahas very low precedence, solambda x: x + 1, 2is a lambda followed by2. Wrap it in parentheses when passing it along with other arguments. - Alternatives:
operator.itemgetter,operator.attrgetterandoperator.methodcallerare faster and more explicit for common keys; comprehensions usually replacemapandfilterwith lambdas. - Same type as
deffunctions, so closures, attributes andcallable()behave identically. - Performance is the same as an equivalent
deffunction.