Home > Articles

This chapter is from the book

This chapter is from the book

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.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.