Skip to content
Tutorials Center
My learning

Topics

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.

Python
square = lambda x: x * x
square(4)     # 16

Try it

Python Lambdas as key functions

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.

Python Late binding and limits

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

Python
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 a def. 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 use functools.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 recommends def instead).
  • No annotations or docstring in the lambda itself.
  • Precedence. lambda has very low precedence, so lambda x: x + 1, 2 is a lambda followed by 2. Wrap it in parentheses when passing it along with other arguments.
  • Alternatives: operator.itemgetter, operator.attrgetter and operator.methodcaller are faster and more explicit for common keys; comprehensions usually replace map and filter with lambdas.
  • Same type as def functions, so closures, attributes and callable() behave identically.
  • Performance is the same as an equivalent def function.