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, so 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)` applies `f` to every item, lazily.
- -`filter(predicate, iterable)` keeps only items where `predicate` is truthy, lazily.
- -`functools.reduce(f, iterable)` folds 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.
Interview Signal is part of Pro
See a real weak answer next to a real strong one for this exact topic.
Quiz is part of Pro
Test what you just read with a short quiz, and bank the XP.