Sitemap

Member-only story

Reduce Function in Python

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.

Give it :👏👏👏👏:
If you found this guide helpful , why not show some love? Give it a Clap 👏, and if you have questions or topics you’d like to explore further, drop a comment 💬 below 👇.
If you appreciate my hard work please follow me. That is the only way I can continue my passion.

If you need mentorship in Data Science or have any questions, feel free to reach out directly at datasciencejourney100@gmail.com.

--

--

Rina Mondal
Rina Mondal

Written by Rina Mondal

I truly enjoy writing articles. If you appreciate my hard work, please follow me. Your encouragement helps me continue pursuing my passion.