Built-in Functions
map, filter, reduce
Functional programming utilities for data transformation pipelines
Interview: Common in interviews — understanding when to use these vs comprehensions is key
map, filter, and reduce are the three pillars of functional programming in Python. map transforms each element, filter selects elements, and reduce accumulates elements into a single result. While list comprehensions are often preferred for readability, these functions remain important for working with existing named functions and understanding functional patterns.
map(func, *iterables)
- Applies func to each element: Returns a lazy iterator (not a list in Python 3)
- Multiple iterables:
map(add, list1, list2)— passes one element from each to func - With built-in functions:
list(map(str, [1, 2, 3]))— cleaner than lambda when using named functions - Comprehension alternative:
[f(x) for x in iterable]is generally preferred
filter(func, iterable)
- Keeps truthy elements: Returns elements where func(element) returns True
- None as function:
filter(None, iterable)removes all falsy values (0, None, "", [], etc.) - Comprehension alternative:
[x for x in iterable if f(x)]
reduce(func, iterable[, initial])
- From functools: Must be imported —
from functools import reduce - Binary function: func takes two arguments — accumulator and current element
- Initial value: Optional starting value for the accumulator
- Common uses: Sum, product, finding min/max, building nested dicts
When to Use map/filter vs Comprehensions
Use map/filter when you already have a named function: map(str.upper, words) is clean. Use comprehensions when you need a lambda: [w.upper() for w in words] is more readable than map(lambda w: w.upper(), words).
Use Cases
Data transformation pipelines: clean → filter → transform → aggregate
Converting types in bulk: list(map(str, numbers)) or list(map(int, strings))
Functional data processing without side effects
Accumulating results with reduce: products, running totals, building structures
Lazy evaluation with map/filter for memory-efficient processing of large datasets
Common Mistakes
Forgetting that map/filter return iterators in Python 3 — use list() to see results
Using lambda with map/filter when a comprehension would be more readable
Forgetting to import reduce from functools — it's not a built-in anymore
Not providing an initial value to reduce — can cause errors on empty iterables
Using reduce for simple sums when sum() is cleaner and faster