The accumulator (acc) collects the result at each step.
What is reduce()?
reduce() folds a list into a single value by applying a function sequentially to each element.
from functools import reduce
numbers = [1, 2, 3, 4, 5]
# Old way
total = 0
for num in numbers:
total = total + num
# With reduce()
total = reduce(lambda acc, x: acc + x, numbers)
print(total) # 15
Syntax
from functools import reduce
reduce(function, iterable, initial_value)
function— takes 2 arguments: accumulator and current elementiterable— list, tuple, etc.initial_value— optional starting value for the accumulator
How does reduce() work?
numbers = [1, 2, 3, 4, 5]
result = reduce(lambda acc, x: acc + x, numbers)
Step 1: acc=1, x=2 → 3
Step 2: acc=3, x=3 → 6
Step 3: acc=6, x=4 → 10
Step 4: acc=10, x=5 → 15
Result: 15
The accumulator (acc) collects the result at each step.
Core Examples
Sum
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda acc, x: acc + x, numbers)
print(total) # 15
# With initial value
total = reduce(lambda acc, x: acc + x, numbers, 10)
print(total) # 25 (10 + 1 + 2 + 3 + 4 + 5)
Product
numbers = [1, 2, 3, 4, 5]
product = reduce(lambda acc, x: acc * x, numbers)
print(product) # 120
# Factorial
def factorial(n):
return reduce(lambda acc, x: acc * x, range(1, n + 1), 1)
print(factorial(5)) # 120
print(factorial(0)) # 1
Practical Examples
Flatten a nested list
nested = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flattened = reduce(lambda acc, lst: acc + lst, nested, [])
print(flattened) # [1, 2, 3, 4, 5, 6, 7, 8, 9]
Sum values from a list of dicts
sales = [
{"product": "Phone", "revenue": 500},
{"product": "Laptop", "revenue": 1200},
{"product": "Mouse", "revenue": 25}
]
total_revenue = reduce(lambda acc, sale: acc + sale["revenue"], sales, 0)
print(total_revenue) # 1725
Function pipeline
def add_10(x): return x + 10
def multiply_2(x): return x * 2
def square(x): return x ** 2
functions = [add_10, multiply_2, square]
result = reduce(lambda acc, func: func(acc), functions, 5)
# 5 → add_10 → 15 → multiply_2 → 30 → square → 900
print(result) # 900
map + filter + reduce Combo
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Even → double → sum
result = reduce(
lambda acc, x: acc + x,
map(lambda x: x * 2, filter(lambda x: x % 2 == 0, numbers)),
0
)
print(result) # 60
# Step by step:
# filter: [2, 4, 6, 8, 10]
# map: [4, 8, 12, 16, 20]
# reduce: 4 + 8 + 12 + 16 + 20 = 60
Initial Value
The initial value is required when working with an empty list or when the result type differs from the element type:
# Empty list without initial — error!
result = reduce(lambda acc, x: acc + x, [])
# TypeError: reduce() of empty sequence with no initial value
# With initial — OK
result = reduce(lambda acc, x: acc + x, [], 0)
print(result) # 0
# Different result type
numbers = [1, 2, 3, 4, 5]
result = reduce(
lambda acc, x: {**acc, str(x): x ** 2},
numbers,
{} # Initial value is a dict
)
print(result) # {'1': 1, '2': 4, '3': 9, '4': 16, '5': 25}
Common Mistakes
Mistake 1: Forgot to import
# ❌ ERROR
result = reduce(lambda acc, x: acc + x, [1, 2, 3])
# NameError: name 'reduce' is not defined
# ✅ CORRECT
from functools import reduce
result = reduce(lambda acc, x: acc + x, [1, 2, 3])
Mistake 2: Function doesn’t return a value
def add_bad(acc, x):
acc + x # Missing return!
result = reduce(add_bad, [1, 2, 3])
print(result) # None
# ✅ CORRECT
def add_good(acc, x):
return acc + x
result = reduce(add_good, [1, 2, 3])
print(result) # 6
When to use reduce()
Use reduce():
- Complex folding logic (not just sum/max/min)
- Non-standard accumulation operations
- Sequential function pipelines
Don’t use reduce():
- Sum → sum(numbers)
- Max/min → max() / min()
- String joining → "".join(words)
💬 Comments (0)
No comments yet
Be the first to share your opinion about this article!