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.

Easy Python 3.9+ Aug 9, 2026 Functions & basics 12 views 0 copies

Python code

22 lines
Python 3.9+
from 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

stdout
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

  1. Add an initializer argument, e.g. reduce(operator.add, numbers, 0), to handle empty iterables safely
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Functions & basics

Related tutorials and quizzes for this topic.