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 list comprehensions. It also assumes you know that a function is a value you can pass around, which the previous chapter covered.
The syntax
A lambda expression creates a small function without a def statement and without a name. The form is:
lambda parameters: expressionThe parts are:
- The keyword
lambda. - A parameter list, written without parentheses.
- A colon.
- A single expression. Its value is what the function returns.
There is no return keyword. The result of the expression is returned automatically.
These two definitions behave the same way:
def square_def(n):
return n * n
square_lambda = lambda n: n * n
print(square_def(4)) # 16
print(square_lambda(4)) # 16A lambda is an expression
A def is a statement, so it must stand on its own line. A lambda is an expression, so it can appear anywhere a value can: as an argument, inside a list, or as a dictionary value.
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 created, passed to sorted as the key argument, and then discarded. It never needs a name, which is the main reason lambdas exist.
You can also call a lambda immediately by wrapping it in parentheses. This is rarely useful, but it shows that the lambda is just a value:
print((lambda a, b: a + b)(2, 3)) # 5Parameters
Lambda parameters follow the same rules as in def. You can use zero parameters, defaults, *args, **kwargs and keyword-only parameters.
no_args = lambda: "ready"
with_default = lambda name, greeting="Hello": f"{greeting}, {name}"
variadic = lambda *args, **kwargs: (args, kwargs)
print(no_args()) # ready
print(with_default("Ada")) # Hello, Ada
print(with_default("Ada", "Hi")) # Hi, Ada
print(variadic(1, 2, x=3)) # ((1, 2), {'x': 3})Using conditions and returning several values
The body must be one expression, but a conditional expression (a if test else b) counts as one. This gives you branching without an if statement.
sign = lambda n: "negative" if n < 0 else "non-negative"
print(sign(-2)) # negative
print(sign(5)) # non-negativeTo return several values, wrap them in parentheses so Python sees one tuple:
min_max = lambda items: (min(items), max(items))
print(min_max([4, 9, 1])) # (1, 9)Common errors
| Mistake | What happens | Fix |
|---|---|---|
| `lambda x: return x` | `SyntaxError`. `return` is a statement. | Write `lambda x: x`. |
| `lambda x: x, 1` | Python reads a tuple of a lambda and `1`. | Use parentheses: `(lambda x: x)`. |
| `f = lambda x: x * 2` | It works, but the function's name shows as `<lambda>` in tracebacks. | Use `def f(x): return x * 2`. |
| `lambda x: print(x)` for a multi-step task | Only one expression is allowed. | Use `def`. |
You can see the missing name directly:
def named(x):
return x
anonymous = lambda x: x
print(named.__name__) # named
print(anonymous.__name__) # <lambda>The full list of things a lambda cannot contain is the subject of the next chapter.
Exercise
Write a lambda that takes two numbers and returns the larger one, without calling max. Then use it to compute the larger of 7 and 12.
Show answer
larger = lambda a, b: a if a > b else b print(larger(7, 12)) # 12 The conditional expression is a single expression, so it is allowed as the lambda body.