logo

Understanding functools.reduce in Python

O

Ohidur Rahman Bappy

MAR 22, 2025

Understanding functools.reduce in Python

The reduce() function is part of the functools module in Python. Unlike the map and filter functions, which return iterables, reduce() aggregates all elements in an iterable into a single cumulative value.

How reduce() Works

The reduce() function takes a function and an iterable as its arguments. It applies the given function cumulatively to the elements of the iterable from left to right. The result of applying the function to the first two elements becomes the first argument in the next call, and so on, until all elements have been processed.

Here's an illustrative example:

import functools

def mult(x, y):
    print("x=", x, " y=", y)
    return x * y

fact = functools.reduce(mult, range(1, 4))
print('Factorial of 3:', fact)

Result:

x= 1 y= 2
x= 2 y= 3
Factorial of 3: 6

Example: Calculating Factorial

In the example above, we define a function mult() that multiplies two numbers. We use reduce() with this function and a range of numbers from 1 to 3. This effectively computes the factorial of 3.

The reduce() function simplifies the creation of aggregations such as the factorial calculation, allowing us to express the operation in a concise manner.