Sub topic 14
Choosing between lambda, def and comprehensions
This chapter pulls the earlier ones together into decision rules. It assumes you can write functions with def, use list comprehensions, and understand *args and default arguments. It also assumes you have seen sorted(key=...), map, filter, functools.reduce, closures and functools.partial.
Python usually gives you several ways to write the same logic. The choice rarely changes the result. It changes how easily the next reader can understand, test and debug the code. The rules below are defaults you can break when there is a reason.
The three tools and what each is for
- A lambda is an anonymous function whose body is a single expression. It is best when the function is tiny, used once, and passed straight to another function.
- A def statement creates a named function. It can hold statements, multiple lines, a docstring, annotations and decorators. It is the default for anything you name, reuse or test.
- A comprehension (list, set, dict or generator expression) builds a collection from an iterable with an optional filter. It is the default for "transform and select items".
The decision depends mostly on three questions. Do you need a name? Is the logic more than one simple expression? Are you building a collection or just passing behavior?
When a lambda is the right choice
A lambda fits when the function exists only to be handed to something else, and the body reads at a glance. The most common case is a sort key.
people = [("Ana", 31), ("Bo", 25), ("Cy", 31)]
# Oldest first, ties broken alphabetically
print(sorted(people, key=lambda p: (-p[1], p[0])))
# [('Ana', 31), ('Cy', 31), ('Bo', 25)]Here the lambda is short, has no reuse value, and a name like age_then_name would add little. The same applies to min, max, itertools.groupby keys and callbacks that take one short expression.
A lambda also works as a lightweight entry in a dispatch table, when each entry is trivial:
import operator
ops = {
"+": operator.add,
"-": operator.sub,
"*": operator.mul,
"max": lambda a, b: a if a >= b else b,
}
print(ops["+"](2, 3)) # 5
print(ops["max"](2, 3)) # 3Notice that three of the four entries use operator functions instead of lambdas. That leads to the next rule.
Prefer an existing function over a lambda
A lambda that only wraps another function or an indexing operation adds noise. Pass the underlying function instead.
| Instead of | Write |
|---|---|
| `lambda p: p[1]` | `operator.itemgetter(1)` |
| `lambda o: o.age` | `operator.attrgetter("age")` |
| `lambda a, b: a + b` | `operator.add` |
| `lambda s: len(s)` | `len` |
| `lambda s: s.lower()` | `str.lower` |
| `lambda x: f(x, 10)` | `functools.partial(f, 10)` or a `def` |
words = ["Banana", "apple", "Cherry"]
print(sorted(words, key=lambda s: s.lower())) # ['apple', 'Banana', 'Cherry']
print(sorted(words, key=str.lower)) # ['apple', 'Banana', 'Cherry']The version with str.lower is shorter and avoids one extra function call per item. The gain is usually small, so choose it for clarity, not speed.
Be careful with partial. It fixes arguments by position or keyword at creation time, so partial(f, 10) is lambda x: f(10, x), not lambda x: f(x, 10). When the fixed argument is not first, use a keyword argument in the partial call or write a def.
When to write a def
Use def in any of these cases:
- The logic needs a statement. Lambdas cannot contain assignments,
ifstatements (only the conditional expression), loops,tryorwith. - You need a name. Named functions appear in tracebacks as
shipping_key, not<lambda>. They can have docstrings and be imported and tested. - You reuse it. If the same lambda appears twice, it should be a function.
- The expression is hard to read. Nested conditional expressions inside a lambda are a warning sign.
orders = [
{"id": 1, "express": False, "created": 5},
{"id": 2, "express": True, "created": 9},
{"id": 3, "express": True, "created": 2},
]
def shipping_key(order):
"""Express orders first, then oldest first."""
priority = 0 if order["express"] else 1
return (priority, order["created"])
print([o["id"] for o in sorted(orders, key=shipping_key)])
# [3, 2, 1]You could squeeze this into lambda o: (0 if o["express"] else 1, o["created"]). It would work, but the named version documents the intent, can be unit tested alone, and shows its name in an error.
Do not assign a lambda to a name
This pattern defeats the purpose of a lambda:
square = lambda x: x * x # PEP 8 discourages this
def square_def(x):
return x * x
print(square.__name__) # <lambda>
print(square_def.__name__) # square_defBoth functions behave the same, but the lambda reports <lambda> in tracebacks and reprs, and tools that read __name__ or __qualname__ get less information. If a function gets a name, write it with def. Linters flag this as E731.
When a comprehension beats map and filter
For building a list, set or dict from an iterable, a comprehension is usually clearer than map and filter with lambdas. It states the source, the condition and the output expression in one place, and it needs no list(...) wrapper.
nums = [1, 2, 3, 4, 5, 6]
via_hof = list(map(lambda n: n * n, filter(lambda n: n % 2 == 0, nums)))
via_comp = [n * n for n in nums if n % 2 == 0]
print(via_hof == via_comp) # TrueThe comprehension reads left to right, while the nested version reads from the inside out. Comprehensions also build dicts and sets directly, which map and filter cannot do without a conversion:
words = ["tea", "coffee", "milk"]
lengths = {w: len(w) for w in words if len(w) > 3}
print(lengths) # {'coffee': 6, 'milk': 4}map remains a good choice when you already have a named function and no filter:
words = ["tea", "coffee", "milk"]
print(list(map(len, words))) # [3, 6, 4]
print([len(w) for w in words]) # [3, 6, 4]Both lines are fine. map(len, words) is shorter, and some teams prefer the comprehension for consistency. Do not mix styles within one function just to show variety.
A laziness difference
In Python 3, map and filter return lazy iterators, and a generator expression is also lazy, while a list comprehension builds the whole list at once. If you only need to loop once or feed sum, any or max, use a generator expression and avoid the intermediate list:
nums = [1, 2, 3, 4, 5, 6]
print(sum(n * n for n in nums if n % 2 == 0)) # 56
print(any(n > 5 for n in nums)) # TrueRemember that an iterator can be consumed only once. If you need to loop over the result twice or take its len, build a list.
reduce: usually a named alternative exists
functools.reduce is the right tool when you fold items into a result that no built-in covers. For common cases, a dedicated function is clearer:
| Goal | Prefer |
|---|---|
| Sum | `sum(items)` |
| Maximum or minimum | `max(items)`, `min(items)` |
| All or any true | `all(...)`, `any(...)` |
| Product | `math.prod(items)` |
| Join strings | `"".join(items)` |
from functools import reduce
from math import prod
nums = [1, 2, 3, 4]
print(reduce(lambda acc, n: acc * n, nums, 1)) # 24
print(prod(nums)) # 24Keep reduce for real folds, such as merging a list of dicts or composing functions, and give it a named function if the step is more than a simple operator.
Late binding and closures in your choice
Choosing a lambda inside a loop or comprehension carries one extra risk. A lambda looks up captured variables when it is called, not when it is created.
funcs = [lambda: i for i in range(3)]
print([f() for f in funcs]) # [2, 2, 2]
fixed = [lambda i=i: i for i in range(3)]
print([f() for f in fixed]) # [0, 1, 2]If you create several functions in a loop, either bind the value with a default argument as shown, use functools.partial, or build them with a factory function such as make_multiplier. The factory is usually the most readable, because each call gets its own scope.
Decorators and factories: always def
Decorators and function factories contain an inner function that usually needs a name, a docstring or functools.wraps. Write them with def. A lambda is acceptable only for a one-line factory such as lambda x: x * factor, where the captured variable is clear.
Quick rules of thumb
- Building a list, set or dict from an iterable: comprehension.
- Passing a tiny one-off expression as an argument: lambda.
- Wrapper around indexing, attributes or an operator:
itemgetter,attrgetteroroperator. - Logic with statements, reuse, or a need for a docstring:
def. - Folding with a built-in equivalent: use the built-in. Otherwise
reducewith a clear step. - If you have to explain a lambda in a comment, replace it with a
defand a good name.
Exercises
Exercise
A teammate wrote by_score = lambda r: r["score"] and then calls sorted(rows, key=by_score) and max(rows, key=by_score). Name two problems with the assignment style and give a better version.
Show answer
The lambda is assigned to a name, so it shows as <lambda> in tracebacks and cannot have a docstring, and linters flag it (E731). For simple dictionary access, operator.itemgetter("score") is better: by_score = itemgetter("score"). If more logic is needed later, use def by_score(r): return r["score"].
Exercise
Rewrite list(map(lambda s: s.strip(), filter(lambda s: s != "", lines))) in a clearer form, and say why you chose it.
Show answer
[s.strip() for s in lines if s != ""]. The comprehension states the source, the filter and the output in one place, avoids two lambdas and the list(...) wrapper, and reads left to right. Note that this checks the unstripped string. To drop lines that are only whitespace, use [s.strip() for s in lines if s.strip()].