map/filter/reduce & Functional Tools
You'll learn to
- -Use `map()` and `filter()` to transform and select from an iterable
- -Use `functools.reduce()` to fold an iterable down to a single value
- -Have an informed opinion on when a comprehension is more idiomatic than map/filter
Python offers a set of functional-programming-flavored built-ins - `map`, `filter`, and (via `functools`) `reduce` - for transforming and combining iterables without writing an explicit loop. They are genuinely useful to recognize when reading other people's code, but idiomatic Python often prefers a comprehension instead. This chapter covers both the tools and the judgment call.
map()
`map(function, iterable)` applies `function` to every item and returns a lazy iterator of the results (much like a generator - you typically wrap it in `list(...)` to see the values, or iterate over it directly).
filter()
`filter(predicate, iterable)` keeps only the items for which `predicate` returns a truthy value.
functools.reduce()
`reduce(function, iterable)` repeatedly applies a two-argument function to combine all items into a single accumulated value - it "folds" the sequence down. Unlike `map`/`filter`, there is no comprehension equivalent, so `reduce` (or a plain loop) is the standard tool here.
The Opinionated Take: Comprehensions Usually Win
For simple transform-or-filter logic, most experienced Python developers reach for a list (or generator) comprehension over `map`/`filter` with a `lambda` - comprehensions read left-to-right in plain English ("x for x in numbers if x is even") and avoid the extra `lambda` ceremony. `map`/`filter` earn their keep mainly when you already have a named function (not a lambda) to pass in, or when working with very large lazy pipelines where you want to chain several transformations without an intermediate list at every step.
- -`map(f, iterable)`: apply `f` to every item, lazily.
- -`filter(predicate, iterable)`: keep only items where `predicate` is truthy, lazily.
- -`functools.reduce(f, iterable)`: fold the whole iterable down to one accumulated value.
- -Prefer a comprehension over `map`/`filter` + `lambda` for simple cases; `map` earns its place when you already have a plain named function to apply.