Python Basics — reduce() Function
The reduce() Function
reduce() applies a function cumulatively to the items of an iterable, reducing them to a single value. Think of it as “fold” — folding a list into one result.
Import and Syntax
Unlike map() and filter(), reduce() is in the functools module:
from functools import reduce
reduce(function, iterable[, initial])
function— takes two arguments: accumulator and current itemiterable— the data to reduceinitial(optional) — starting value for the accumulator
How reduce() Works
reduce(f, [a, b, c, d]) computes:
f(f(f(a, b), c), d)
Step 1: result = f(a, b)
Step 2: result = f(result, c)
Step 3: result = f(result, d)
→ final result
Basic Examples
Sum
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda acc, x: acc + x, numbers)
print(total) # 15
# Equivalent to:
# ((((1 + 2) + 3) + 4) + 5) = 15
Product
from functools import reduce
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda acc, x: acc * x, numbers)
print(product) # 120
# Equivalent to:
# ((((1 * 2) * 3) * 4) * 5) = 120
Maximum Value
from functools import reduce
numbers = [34, 12, 89, 56, 23]
maximum = reduce(lambda acc, x: acc if acc > x else x, numbers)
print(maximum) # 89
The Initial Value Parameter
Without an initial value, reduce() uses the first element as the starting accumulator. With one, it starts from the specified value:
from functools import reduce
numbers = [1, 2, 3, 4, 5]
# Without initial value — starts with first element (1)
total = reduce(lambda acc, x: acc + x, numbers)
print(total) # 15
# With initial value of 100
total = reduce(lambda acc, x: acc + x, numbers, 100)
print(total) # 115
# Important: initial value protects against empty iterables
empty = []
# reduce(lambda a, b: a + b, empty) # TypeError: reduce() of empty iterable with no initial value
result = reduce(lambda a, b: a + b, empty, 0) # Safe!
print(result) # 0
Common Reductions
from functools import reduce
data = [10, 20, 30, 40, 50]
# Sum
total = reduce(lambda a, b: a + b, data, 0)
print(f"Sum: {total}") # Sum: 150
# Product
product = reduce(lambda a, b: a * b, data, 1)
print(f"Product: {product}") # Product: 12000000
# Max
maximum = reduce(lambda a, b: a if a > b else b, data)
print(f"Max: {maximum}") # Max: 50
# Min
minimum = reduce(lambda a, b: a if a < b else b, data)
print(f"Min: {minimum}") # Min: 10
# Concatenate strings
words = ["Hello", " ", "World", "!"]
sentence = reduce(lambda a, b: a + b, words)
print(f"Sentence: {sentence}") # Sentence: Hello World!
reduce() vs Built-in Alternatives
Python has built-in functions that cover most reduce() use cases — and they’re clearer and faster:
| Task | reduce() |
Built-in |
|---|---|---|
| Sum | reduce(lambda a,b: a+b, lst) |
sum(lst) |
| Max | reduce(lambda a,b: max(a,b), lst) |
max(lst) |
| Min | reduce(lambda a,b: min(a,b), lst) |
min(lst) |
| All true | reduce(lambda a,b: a and b, lst) |
all(lst) |
| Any true | reduce(lambda a,b: a or b, lst) |
any(lst) |
| Join strings | reduce(lambda a,b: a+b, lst) |
"".join(lst) |
numbers = [1, 2, 3, 4, 5]
# ❌ Don't use reduce for simple operations
from functools import reduce
total = reduce(lambda a, b: a + b, numbers)
# ✅ Use built-in functions
total = sum(numbers)
When reduce() Shines
reduce() is valuable when there’s no built-in that does what you need:
Flattening a List of Lists
from functools import reduce
nested = [[1, 2], [3, 4], [5, 6]]
flat = reduce(lambda acc, lst: acc + lst, nested, [])
print(flat) # [1, 2, 3, 4, 5, 6]
Building a Dictionary
from functools import reduce
pairs = [("name", "Alice"), ("age", 30), ("city", "Bangalore")]
result = reduce(lambda d, pair: {**d, pair[0]: pair[1]}, pairs, {})
print(result) # {'name': 'Alice', 'age': 30, 'city': 'Bangalore'}
Composing Functions
from functools import reduce
def compose(*funcs):
return reduce(lambda f, g: lambda x: f(g(x)), funcs)
double = lambda x: x * 2
add_one = lambda x: x + 1
square = lambda x: x ** 2
transform = compose(double, add_one, square)
print(transform(3)) # double(add_one(square(3))) = double(add_one(9)) = double(10) = 20
Summary
reduce(func, iterable, initial)accumulates items into a single result- Must import from
functools - Always provide an
initialvalue when the iterable might be empty - For
sum,max,min,all,any,join— use the built-in instead reduce()shines for custom accumulations without a built-in equivalent- Think of it as: “fold this list into one value”
Next up: sorted() with Key →