Python Docs
Map, Filter & Reduce
These functional programming helpers let you transform (map), select (filter) and aggregate (reduce) sequences. They are powerful for data pipelines, although list comprehensions are often more readable for simple cases.
map()
map(func, iterable) applies a function to every element, returning a lazy iterator.
nums = [1, 2, 3, 4] doubled = list(map(lambda x: x * 2, nums)) print(doubled) # [2, 4, 6, 8] # Equivalent comprehension: # [x * 2 for x in nums]
filter()
filter(func, iterable) keeps only items where the function returns truthy.
nums = [1, 2, 3, 4, 5] evens = list(filter(lambda x: x % 2 == 0, nums)) print(evens) # [2, 4] # Equivalent: # [x for x in nums if x % 2 == 0]
reduce()
reduce(func, iterable, init) folds a sequence into a single value using a binary function.
from functools import reduce nums = [1, 2, 3, 4] total = reduce(lambda a, b: a + b, nums) print(total) # 10 # Factorial using reduce: fact5 = reduce(lambda a, b: a * b, range(1, 6), 1) print(fact5) # 120
Combining
Chain filter → map → reduce for clean data pipelines.
from functools import reduce
nums = [1, 2, 3, 4, 5, 6]
# Sum of squares of even numbers
result = reduce(
lambda a, b: a + b,
map(lambda x: x * x, filter(lambda x: x % 2 == 0, nums))
)
print(result) # 56Best Practices
- Prefer comprehensions for short, simple transformations.
- Use
reducewhen you naturally “fold” values (sum, product, min/max, joins). - Keep lambdas very small; move complex logic into named functions and pass those to
map/filter. - Combine
filter→map→reducefor functional-style ETL / data-processing pipelines.