Map transforms iteration results, filter selects them, and reduce folds values into one accumulator.
Python map, filter and reduce: iterator timing and reduction identity
Operation contract
The review pipeline filters positive adjustment amounts, maps them into labeled records, then materializes the result once. The deferred operations do not run when map and filter are constructed; their source list is read during consumption. Reduce sums an empty amount sequence using an explicit zero initializer, which defines its identity case.
Failure and ownership boundary
An exhausted iterator does not replay its results. Mutating a source before consuming it can change the answer. For simple transformations, a comprehension can make selection and mapping easier to inspect. A reduction callback also needs an accumulator type and error policy; Python comprehensions: build results without changing the input and Python iterator interview: lazy calls, exhaustion and partial failure expose those decisions.
Working program
from functools import reduce
adjustments = [125, -25, 75]
selected = filter(lambda amount: amount > 0, adjustments)
labeled = map(lambda amount: f"accepted:{amount}", selected)
adjustments.append(50)
print(list(labeled))
print(list(labeled))
print("empty total:", reduce(lambda total, amount: total + amount, [], 0))Output
['accepted:125', 'accepted:75', 'accepted:50']
[]
empty total: 0Costs and limits
Constructing these lazy wrappers retains small iterator state; consuming n entries costs the predicates/transforms over those entries. Materializing accepted results uses O(k) storage for k selected records. A growing accumulator can add numeric or allocation costs.
Common Mistakes
- Constructing map does not snapshot its input.
- Supply a reduction initializer when an empty input is valid.
Connected lessons
Python comprehensions: build results without changing the input, Python iterator interview: lazy calls, exhaustion and partial failure, Python generators: lazy iteration does not make retained output free.
