Reduce Function in Python

Rina Mondal
1 min readApr 5, 2024

--

The “reduce()” function is used to apply a function to an iterable (such as a list) cumulatively to reduce it to a single value. It repeatedly applies the specified function to the elements of the iterable, accumulating the result.

The “reduce()” function is part of the functools module in Python, so you need to import it before using it:

Here’s a simple example:

from functools import reduce
# Define a function to add two numbers
def add(x, y):
return x + y

# Create a list of numbers
numbers = [1, 2, 3, 4, 5]

# Use reduce() to sum up all the numbers in the list
sum_of_numbers = reduce(add, numbers)
print(sum_of_numbers)

# Output: 15 (1 + 2 + 3 + 4 + 5)

In this example, the add() function is used with reduce() to cumulatively sum up all the numbers in the numbers list. The result is the total sum of all the numbers.

--

--

Rina Mondal

I have an 8 years of experience and I always enjoyed writing articles. If you appreciate my hard work, please follow me, then only I can continue my passion.