How to Use functools.reduce in Python
Apply functools.reduce with operator functions and lambda expressions to aggregate lists into sums, products, maximums, and concatenated strings.
Python code
22 linesfrom functools import reduce
import operator
# Sum all numbers in a list using reduce
numbers = [1, 2, 3, 4, 5]
sum_result = reduce(operator.add, numbers)
# Find the maximum value using reduce
max_result = reduce(lambda a, b: a if a > b else b, numbers)
# Multiply all numbers using reduce
product_result = reduce(lambda a, b: a * b, numbers)
# Concatenate strings using reduce
words = ["Python", " ", "is", " ", "awesome"]
concat_result = reduce(lambda a, b: a + b, words)
if __name__ == "__main__":
print(f"Sum: {sum_result}")
print(f"Max: {max_result}")
print(f"Product: {product_result}")
print(f"Concatenation: {concat_result}")
Output
Sum: 15
Max: 5
Product: 120
Concatenation: Python is awesome
How it works
reduce applies a binary function cumulatively to the items of an iterable, reducing it to a single value. The function receives the accumulated result as the first argument and the current item as the second. operator.add and operator.mul are built-in functions that work perfectly with reduce for numeric aggregation. Lambda expressions give full control when you need custom logic, like picking the larger value. The if __name__ == '__main__': guard ensures the print statements only run when the script is executed directly, keeping the module importable.
Common mistakes
- Using reduce when a simple sum() or max() built-in would be clearer and faster
- Forgetting that reduce functions need two arguments — the accumulator and the current item
- Passing an empty iterable without an initializer, which raises TypeError
- Expecting reduce to modify the original list instead of returning a new result
Variations
- Add an initializer argument, e.g. reduce(operator.add, numbers, 0), to handle empty iterables safely
- Use math.prod(numbers) for product or max(numbers) for maximum instead of reduce when applicable
Real-world use cases
- Flattening a list of lists into a single list during data preprocessing.
- Computing a running product across a series of discount factors in a pricing engine.
- Accumulating values across distributed chunks before final aggregation in a map-reduce style job.
Sponsored
More from Functions & basics
- Add Type Hints to Function Parameters and Return in Python easy
- Benchmark list append vs comprehension in Python easy
- Build a Context Manager in Python with contextlib.contextmanager easy
- Build a Progress Callback Function for Loops in Python easy
- Cache expensive function with lru_cache in Python easy
- Calculate Time Difference Across Time Zones in Python easy
Keep learning
Related tutorials and quizzes for this topic.