Sub topic 2
Writing a lambda expression
This chapter assumes you can define and call functions with def, use default values, *args and **kwargs, and read a list comprehension. It covers the syntax of a lambda expression: what each part means, which parameter forms it accepts, and which mistakes cause errors. Later chapters cover where lambdas are most useful and where they run out of room.
What a lambda expression is
A lambda expression creates a function object without a def statement and without a name. It is an expression, so you can write it anywhere Python expects a value: as an argument, inside a list, or on the right side of an assignment.
square = lambda x: x * x
print(square(6)) # 36
print(type(square)) # <class 'function'>The result has the same type as a function made with def. It is called the same way and can be passed around like any other function. The differences lie in how you write it and in what the body may contain.
The anatomy of a lambda
A lambda has three parts: the keyword lambda, an optional parameter list, and a colon followed by one expression. The value of that expression is what the function returns.
These two definitions behave the same way:
def add_def(a, b):
return a + b
add_lambda = lambda a, b: a + b
print(add_def(2, 3)) # 5
print(add_lambda(2, 3)) # 5There is no return keyword in a lambda. The expression after the colon is returned automatically.
Parameters are not wrapped in parentheses. The parentheses you often see around a lambda belong to the code around it. You need them to call a lambda on the spot:
print((lambda a, b: a + b)(2, 3)) # 5Without the outer parentheses, Python would treat (2, 3) as part of the body expression.
Parameter forms
A lambda accepts the same parameter forms as def. Only the body is restricted.
# No parameters
answer = lambda: 42
# Default value
greet = lambda name, greeting="Hello": f"{greeting}, {name}!"
# Arbitrary positional arguments
total = lambda *nums: sum(nums)
# Arbitrary keyword arguments
describe = lambda **kw: sorted(kw.items())
# Keyword-only parameter after a bare *
scaled = lambda x, *, factor=1: x * factor
print(answer()) # 42
print(greet("Ada")) # Hello, Ada!
print(greet("Ada", "Hi")) # Hi, Ada!
print(total(1, 2, 3)) # 6
print(describe(b=2, a=1)) # [('a', 1), ('b', 2)]
print(scaled(3, factor=4)) # 12Inside the body, nums is a tuple and kw is a dictionary, exactly as in a def function. Parameter annotations such as x: int are not available, because the colon already ends the parameter list. A lambda cannot carry type hints on its parameters or its return value.
The body is one expression
The body must be a single expression. An expression is anything that produces a value: arithmetic, a function call, a comparison, a conditional expression, a comprehension, an f-string, or a tuple built in parentheses.
A conditional expression lets a lambda choose between two values:
sign = lambda n: "negative" if n < 0 else "zero" if n == 0 else "positive"
print(sign(-4)) # negative
print(sign(0)) # zero
print(sign(9)) # positiveThe if ... else here is an expression that produces a value. It is not an if statement. Chaining several of them, as above, already makes the line hard to read. If you need more than one branch, a def is usually clearer.
A lambda body can call other functions, including ones with side effects such as print:
shout = lambda text: print(text.upper())
shout("hello") # HELLOThis works because print(...) is an expression. It evaluates to None, which is what shout returns.
Lambda precedence and the tuple trap
lambda has the lowest precedence of any Python operator. The body extends as far to the right as it can, so lambda x: x + 1 if x else 0 means "return (x + 1) if x else 0". The conditional is inside the body.
The comma is the exception. A comma ends the lambda and starts a new item in the surrounding expression:
pair = lambda x: x, 1
print(type(pair)) # <class 'tuple'>
print(pair[1]) # 1This does not define a lambda that returns two values. It builds a tuple whose first item is a lambda and whose second item is 1. To return two values, parenthesize them:
pair = lambda x: (x, 1)
print(pair(5)) # (5, 1)Lambdas have no name of their own
A function made with def stores its name in __name__. A lambda always has the placeholder name <lambda>, no matter what variable you assign it to:
def square_def(x):
return x * x
square_lambda = lambda x: x * x
print(square_def.__name__) # square_def
print(square_lambda.__name__) # <lambda>The placeholder name appears in tracebacks and in repr output, so an error inside a lambda is harder to locate. This is the main reason style guides, including PEP 8, advise against assigning a lambda to a name. If a function needs a name, use def. Reserve lambda for functions that are used once, at the place where they are written.
pairs = [("apple", 3), ("pear", 1), ("fig", 2)]
print(sorted(pairs, key=lambda p: p[1]))
# [('pear', 1), ('fig', 2), ('apple', 3)]Here the lambda is an argument to sorted. It has no name because it needs none. The next chapters cover key functions in detail.
Names inside the body
A lambda body can read variables from the scope where the lambda was written. It looks them up when the lambda is called, not when it is created.
rate = 0.2
with_tax = lambda price: price * (1 + rate)
print(with_tax(100)) # 120.0
rate = 0.5
print(with_tax(100)) # 150.0Changing rate after the lambda was created changes its result. This behavior is behind the late-binding pitfall covered later in the tutorial. For now, remember that a lambda body does not take a snapshot of the names it uses.
Common errors
The mistakes below account for most syntax errors with lambdas.
| You write | What happens | Fix |
|---|---|---|
| `lambda x: return x` | `SyntaxError`, since `return` is a statement | Drop `return`: `lambda x: x` |
| `lambda x: y = x` | `SyntaxError`, since assignment is a statement | Use a `def`, or an expression without assignment |
| `lambda x, y` | `SyntaxError`, missing colon | `lambda x, y: x + y` |
| `lambda (a, b): a + b` | `SyntaxError`, tuple parameters were removed in Python 3 | `lambda p: p[0] + p[1]` |
| `lambda x: x, 1` | Creates a tuple, not a two-value function | `lambda x: (x, 1)` |
| `f = lambda x: x + 1; f` | Prints a function object, does not call it | Call it: `f(3)` |
Summary of the rules
- A lambda is an expression that evaluates to a function object.
- Its parameters follow the same rules as
def, without annotations. - Its body is exactly one expression, and the value of that expression is returned.
- Its
__name__is<lambda>, which makes tracebacks less informative. - Names in the body are looked up at call time, in the scope where the lambda was written.
Exercise
Write a single lambda that takes a string s and an optional keyword-only argument width (default 5), and returns s padded with spaces on the right to at least width characters. Then explain why pad = lambda s, width=5: s.ljust(width), 0 does not do what you might expect.
Show answer
pad = lambda s, *, width=5: s.ljust(width). For example, pad("ab") returns "ab " and pad("ab", width=3) returns "ab ". In the second version the comma after the lambda body ends the lambda, so the whole line assigns a tuple (<lambda>, 0) to pad. Calling pad("ab") raises TypeError: 'tuple' object is not callable. Parenthesizing the body would not help here, because the trailing , 0 was not meant to be returned at all.
Exercise
What does each line print, and which one raises an error?
1. print((lambda: "hi")())
2. print((lambda x, y=2: x * y)(4))
3. print((lambda *a: len(a))(1, 2, 3))
4. print((lambda x: x = 1)(0))
Show answer
Line 1 prints hi. Line 2 prints 8, because y defaults to 2. Line 3 prints 3, because a is the tuple (1, 2, 3). Line 4 raises a SyntaxError before anything runs, because x = 1 is an assignment statement and cannot be the body of a lambda.