Search⌘ K

Functools Reduce

Explore how to apply Python's functools reduce to combine elements of iterables using custom functions. Understand the role of the initializer and how reduce handles special cases, enabling efficient data reduction.

functools's reduce function

If the reducing functions discussed in the previous lessons don’t meet your needs, don’t worry. You can create your own using the reduce function.

This function lets you define your own behavior. For example, suppose we want to reduce a list by multiplying the elements. We can do the following:

Python 3.8
import functools, operator
a = [2, 3, 5, 2]
print(functools.reduce(operator.mul, a)) # 60

Remember that ...