Sub topic 14
Choosing between lambda, def and comprehensions
This chapter assumes you can write functions with def, read list comprehensions, and have seen lambda, sorted with a key, map, filter and the operator module. Here you pull those pieces together into a decision rule.
The working model
The three tools overlap, but each has a main job:
- A lambda is a one-expression function used once, usually as an argument.
- A def is a named function. It can hold several statements, a docstring and tests.
- A comprehension builds a list, set or dictionary from an iterable, with an optional condition.
The question is rarely "which one works?" because all three usually do. Ask which one a reader understands fastest.
Lambda or def
Use a lambda inline as a short key or callback. Switch to def when the logic needs several steps, a name that explains it, or reuse.
from operator import itemgetter
pairs = [("apple", 3), ("pear", 1), ("fig", 2)]
print(sorted(pairs, key=lambda p: p[1]))
print(sorted(pairs, key=itemgetter(1)))
def shipping_rank(order):
country, weight = order
if country == "US":
return (0, weight)
return (1, -weight)
orders = [("DE", 2), ("US", 5), ("US", 1), ("FR", 4)]
print(sorted(orders, key=shipping_rank))
# [('pear', 1), ('fig', 2), ('apple', 3)]
# [('pear', 1), ('fig', 2), ('apple', 3)]
# [('US', 1), ('US', 5), ('FR', 4), ('DE', 2)]The first two calls give the same result. When the lambda only indexes an item, itemgetter states the intent more directly. shipping_rank needs a branch, which a lambda cannot hold as a statement. As a def, it gets a name that documents the rule.
Comprehension or map and filter
For building a list, a comprehension is usually clearer. It reads left to right and needs no lambda.
nums = [1, 2, 3, 4, 5, 6]
squares_of_evens = [n * n for n in nums if n % 2 == 0]
as_text = list(map(str, nums))
print(squares_of_evens) # [4, 16, 36]
print(as_text) # ['1', '2', '3', '4', '5', '6']map(str, nums) is fine because it passes an existing function and needs no lambda. Once you write map(lambda ...) or filter(lambda ...), a comprehension is almost always shorter. map and filter also return lazy iterators, which helps with large inputs. A generator expression gives the same laziness: (n * n for n in nums).
Common errors
- Naming a lambda. Writing
square = lambda x: x * xgives you a function with no useful name in tracebacks. Usedef square(x): return x * x. - Cramming logic into a lambda. Nested conditional expressions in a lambda are hard to read. Move them into a
def. - Lambdas in loops. A lambda created in a loop looks up the loop variable when it is called. Bind it with a default argument (
lambda i=i: i) or usefunctools.partial. - Over-nested comprehensions. More than two
forclauses, or a condition you must reread, is a signal to use a loop or a helper function. - Side effects in comprehensions. Do not write
[print(x) for x in items]. Use a plainforloop.
Quick guide
| Situation | Best choice |
|---|---|
| Sort by one field | `itemgetter` or a short lambda |
| Transform and filter into a list | Comprehension |
| Apply an existing function to every item | `map(func, items)` |
| Multi-step or reusable logic | `def` |
| Fix some arguments of a function | `functools.partial` |
| Fold a sequence into one value | `reduce`, or `sum`, `max` and similar when they fit |
Exercise
Rewrite clean = lambda lines: list(map(lambda s: s.strip(), filter(lambda s: s, lines))) in a clearer style. Which tools did you pick, and why?
Show answer
Use a def with a comprehension: def clean(lines): return [s.strip() for s in lines if s]. The comprehension replaces both the map and filter lambdas, and the def gives the function a real name in tracebacks. Note that if s filters out empty strings before stripping, matching the original order.