Python reduce - Calculate factorials and GCD to use functools.reduce in Python

The reduce() in the functools module repeats the function recursively.

from functools import reduce

a = [1, 2, 3, 4]


def add(x, y):
    return x + y


v = reduce(add, a)

print(v)  # 10

reduce(function, sequence[, initial])

In Python 3.8.5, the arguments of reduce() are the function, sequence, and initial (optional). In the above example, the reduce() executes add() 3 times.

add(1 + 2)
add(? + 3)
add(? + 4)

First, add takes 1 and 2 from a and returns 3. Second, add takes the outcome (3) and the next element in a (3) and returns 6. Third, add takes the outcome (6) and the next element in a (4) and returns 10. Therefore, reduce(add, a) returns 10.

Calculate factorials

We can easily calculate factorial of integer in Python.

from functools import reduce

a = [2, 3, 4, 5, 6]


def mul(x, y):
    return x * y


v = reduce(mul, a)

print(v)  # 720

mul() multiplies values and reduce() calls it recursively.

mul(2 * 3)
mul(6 * 4)
mul(24 * 5)
mul(120 * 6)

GCD

GCD (Greatest common divisor) of integers can be calculated using reduce(). math.gcd returns GCD of only 2 numbers so reduce() is needed to get GCD of more than 2 integers. More details: Python GCD.

import math
from functools import reduce


def f(a, b):
    return math.gcd(a, b)


nums = [32, 40, 24, 56, 16]

g = reduce(f, nums)
print(g)  # 8

Actually, the f doesn't need.

import math
from functools import reduce

nums = [32, 40, 24, 56, 16]

g = reduce(math.gcd, nums)

print(g)  # 8

The difference of reduce() and accumulate()

import functools
import itertools
import operator

a = [1, 2, 3, 4]
b = itertools.accumulate(a, operator.mul)
c = functools.reduce(operator.mul, a)

for i in b:
    print(i)

# 1
# 2
# 6
# 24

print(c)  # 24

Both are similar but the accumulate() returns all the calculated values. Superficially, the accumulate() seems more useful than the reduce().

Python Functools

Python Tutorial