Part 10 / Topic 4 of 11
Functional tools: map, filter, reduce
Functional programming means building programs by passing functions to other functions. Three classic tools:
map(f, items)→ applyfto every item.filter(f, items)→ keep items wheref(item)is true.functools.reduce(f, items, start)→ combine all items into one value, two at a time.
Think of a factory line: map paints every box, filter removes broken boxes, reduce stacks all boxes into one pallet.
A lambda (Part 5) is a tiny one-line function without a name: lambda p: p * 2.
Real-world example: add 18% GST to a price list.
from functools import reduce
prices = [499, 1299, 89, 2499]
with_gst = map(lambda p: round(p * 1.18, 2), prices)
print(with_gst) # <map object at 0x...> (address varies; lazy)
print(list(with_gst)) # [588.82, 1532.82, 105.02, 2948.82]
print(list(filter(lambda p: p >= 500, prices))) # [1299, 2499]
total = reduce(lambda running, p: running + p, prices, 0)
print(total) # 4386
map and filter are lazy: they make values only when you loop over them (or call list()). Section 8 explains why that is useful.
How reduce works on [499, 1299, 89, 2499] with start 0:
0 + 499 = 499
499 + 1299 = 1798
1798 + 89 = 1887
1887 + 2499 = 4386
Comprehension or map/filter?
prices = [499, 1299, 89, 2499]
print(list(map(str, prices))) # ['499', '1299', '89', '2499']
print([p * 2 for p in prices if p >= 500]) # [2598, 4998]
print(list(map(lambda p: p * 2, filter(lambda p: p >= 500, prices)))) # same
| Use | When |
|---|---|
| comprehension | most of the time, especially with a condition |
map |
you already have a named function: map(str, items), map(str.upper, names) |
reduce |
rarely; prefer sum, max, min, "".join when they fit |
🔍 Going deeper:
reducemoved from built-ins intofunctoolsin Python 3, because Python's creator found loops andsum()clearer in most cases.
Full program: examples/02_functional_tools.py.
Read more: the official functools documentation.
Done here? The practice set for Part 10 — 8 exercises with solutions — is on the part page.