Python Reduce Function: Should You Use It or Not? — Codefather

Claudio Sabato
9 min readJun 22, 2021

Python’s reduce function is one of those topics you encounter the more you code in Python. It might sound complex, but is that really the case?

The Python reduce function applies a function of two arguments to the items of an iterable and it returns a single value. The function is applied to two items at a time from left to right until all the items of the iterable are processed. In other words, the function passed to reduce() is applied cumulatively to the iterable.

We will work with a few examples that use the reduce function to make sure you understand how to use it.

Let’s start coding!

How Does Reduce Work in Python?

In this section, we will go through an example of the Python reduce function.

The Python reduce() function is part of the functools module, this is a Python module that contains higher-order functions (act on or return other functions).

The functools.reduce() function takes a function and an iterable as arguments.

functools.reduce(function, iterable)

The reduce operation doesn’t return multiple values, it just returns a single value.

The reduce function reduces an iterable to a single value using a function (or any callable object) passed to it.

Here are the steps reduce follows to generate its result:

  1. It applies the function to the first two elements of the iterable and it generates a result.
  2. The function is then applied to the result of the previous step and to the next element in the iterable.
  3. The process continues until all the items in the iterable are processed.
  4. The final result is returned by the reduce function.

Let’s see how to reduce a list.

Write a function that adds two numbers:

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

Then import the reduce function from the functools module, apply the function to a list of numbers, and print the result.

--

--

Claudio Sabato

Claudio Sabato is an IT expert with over 15 years of professional experience in Python/Bash programming, Linux Systems Administration and IT Systems Design.