Lambdas in Python

Create anonymous functions using the lambda keyword. Similar to Ruby’s blocks, etc. JavaScript has this, too.

Source

Find source code on GitHub.

Syntax

The Python language defines the lambda expression:

lambda <parameters>: <expression>

This is equivalent to creating:

def <lambda>(parameters):
    return <expression>

For example,

lambda x: x * 2

This lambda:

  • accepts a single argument (x)
  • evaluates the expression (x * 2)
  • returns the value of the expression

Lambdas can be stored in a variable and invoked later just like a function:

>>> double_it = lambda x: x * 2
>>> double_it(2)
4
>>> double_it(3)
6

Lamdas may also be passed directly into a function:

def accepts_a_function_object(function_object):
    function_object()

accepts_a_function_object(lambda: print("In the lambda"))

Python will automatically bind the lambda to the argument.

Multi-line Lambdas

Lambdas must not be multi-line! This is a language design decision; see Guido’s blog post. If you need a multi-line lambda, he recommends using a “named function nested in the current scope”.

With the return keyword

Lambdas must not return a value! This is by design - lambdas automatically evaluate and return their expression.

Examples

No Arguments

>>> the_lambda = lambda: 42
>>> the_lambda()
42

One Argument

>>> the_lambda = lambda x: x
>>> the_lambda(42)
42

Two Arguments

>>> the_lambda = lambda x, y: x + y
>>> the_lambda(41, 1)
42

Further Reading