Map, Filter, and Reduce in Python
Mastering Map, Filter, and Reduce in Python: A Comprehensive Guide
Section titled “Mastering Map, Filter, and Reduce in Python: A Comprehensive Guide”map(), filter(), and reduce() are the classic tools of functional programming. Each takes a function and applies it across an iterable: map transforms every item, filter selects items that pass a test, and reduce combines all items into a single value. They pair naturally with lambda functions. In this guide, we’ll explore each one with examples and compare them to comprehensions.
What is Functional Programming?
Section titled “What is Functional Programming?”Functional programming treats functions as values you can pass around. Instead of writing explicit loops, you describe what transformation to apply and let the tool handle the iteration. map, filter, and reduce are the three building blocks.
| Tool | Purpose | Result |
|---|---|---|
map(func, iterable) | Apply func to every item | An iterator of transformed items |
filter(func, iterable) | Keep items where func returns True | An iterator of kept items |
reduce(func, iterable) | Combine items pairwise into one value | A single value |
The map() Function
Section titled “The map() Function”map() applies a function to every element of an iterable and returns a map object (an iterator). Convert it to a list to see the results.
The syntax of the map() function in Python is as follows:
map(function, iterable)numbers = [1, 2, 3, 4]
def square(n):
return n * n
squared = map(square, numbers)
print(list(squared))Output:
C:\Users\Your Name> python map_basic.py
[1, 4, 9, 16]Most often map is used with a lambda:
numbers = [1, 2, 3, 4]
squared = map(lambda n: n * n, numbers)
print(list(squared))You can also pass multiple iterables — the function then receives one item from each:
a = [1, 2, 3]
b = [10, 20, 30]
sums = map(lambda x, y: x + y, a, b)
print(list(sums))Output:
C:\Users\Your Name> python map_multi.py
[11, 22, 33]The filter() Function
Section titled “The filter() Function”filter() keeps only the elements for which the function returns True. It also returns an iterator.
The syntax of the filter() function in Python is as follows:
filter(function, iterable)numbers = [1, 2, 3, 4, 5, 6]
evens = filter(lambda n: n % 2 == 0, numbers)
print(list(evens))Output:
C:\Users\Your Name> python filter_basic.py
[2, 4, 6]The reduce() Function
Section titled “The reduce() Function”reduce() repeatedly applies a function of two arguments to the items of an iterable, accumulating them into a single value. Unlike map and filter, it lives in the functools module and must be imported.
The syntax of the reduce() function in Python is as follows:
from functools import reduce
reduce(function, iterable, initializer)from functools import reduce
numbers = [1, 2, 3, 4]
total = reduce(lambda acc, n: acc + n, numbers)
print(total)Output:
C:\Users\Your Name> python reduce_sum.py
10Diagram:
graph LR
A["1 + 2 = 3"] --> B["3 + 3 = 6"]
B --> C["6 + 4 = 10"]
C --> D["Result: 10"]
reduce accepts an optional initializer — the starting value for the accumulator. It is safer because it defines the result for an empty iterable.
from functools import reduce
numbers = [1, 2, 3, 4]
product = reduce(lambda acc, n: acc * n, numbers, 1) # start at 1
print(product)Output:
C:\Users\Your Name> python reduce_init.py
24map / filter vs. Comprehensions
Section titled “map / filter vs. Comprehensions”A list comprehension can do everything map and filter do, and is often considered more Pythonic and readable.
numbers = [1, 2, 3, 4, 5, 6]
# map + filter
result_fp = list(map(lambda n: n * n, filter(lambda n: n % 2 == 0, numbers)))
# equivalent comprehension
result_comp = [n * n for n in numbers if n % 2 == 0]
print(result_fp, result_comp)Output:
C:\Users\Your Name> python vs_comprehension.py
[4, 16, 36] [4, 16, 36]Visualize it
Section titled “Visualize it”reduce is the trickiest of the three: it carries an accumulator across the list,
combining it with one item at a time to collapse everything into a single value. Here it
folds a list into its sum — watch the accumulator grow as each item is consumed:
Conclusion
Section titled “Conclusion”map, filter, and reduce apply a function across an iterable in three different ways: map transforms every item, filter selects the items that pass a test, and reduce collapses the whole iterable into one value. map and filter are built in and return lazy iterators; reduce lives in functools. While comprehensions often replace map and filter more readably, reduce remains the go-to for accumulation. For more hands-on examples and in-depth tutorials, explore our resources on Python Central Hub!
Try it: Map, Filter, and Reduce Exercises
Section titled “Try it: Map, Filter, and Reduce Exercises”Exercise 1 – map()
Section titled “Exercise 1 – map()”Exercise 2 – filter()
Section titled “Exercise 2 – filter()”Exercise 3 – reduce()
Section titled “Exercise 3 – reduce()”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading