Skip to content

Lambdas

This short sub-section provides additional information on lambdas as they are used commonly in Python code due to their conciseness. For a complete description of lambdas, see the official Python documentation here and here which describes lambdas as:

Lambda expressions (sometimes called lambda forms) are used to create anonymous functions. The expression lambda parameters: expression yields a function object. The unnamed object behaves like a function object defined with:

def <lambda>(parameters):
    return expression

Note that functions created with lambda expressions cannot contain statements or annotations.

And

Small anonymous functions can be created with the lambda keyword. This function returns the sum of its two arguments: lambda a, b: a+b. Lambda functions can be used wherever function objects are required. They are syntactically restricted to a single expression. Semantically, they are just syntactic sugar for a normal function definition. Like nested function definitions, lambda functions can reference variables from the containing scope:

>>> def make_incrementor(n):
...    return lambda x: x + n
...
>>> f = make_incrementor(42)
>>> f(0)
42
>>> f(1)
43

Python lambdas are explained clearly with some examples at W3 Schools. A more comprehensive example can be found at Real Python.