DEV Community

Cover image for Python reduce() function
Chris Bongers
Chris Bongers

Posted on • Originally published at daily-dev-tips.com

Python reduce() function

After looking into the Python filter function and the Python map function, let's take a look at how the reduce works.

The reduce function can be used to do calculations on a set of objects.
For instance, we can count all prices from a dictionary or get an average number.

Reduce() function in Python

Let's look at how the reduce syntax looks.

from functools import reduce

result = reduce(myFunction, input)
Enter fullscreen mode Exit fullscreen mode

This is not much different than we saw with filter and map. The big difference is that we have to import the reduce function.

The real difference lies in the myFunction we are going to make.

This function takes two arguments instead of one, where it receives a new value and the initial value.

from functools import reduce

input = [12, 5, 23, 1]

def myFunction(a, b):
    return a + b

result = reduce(myFunction, input)
print(result)

# 41
Enter fullscreen mode Exit fullscreen mode

With this function we loop over each input number and plus it. However Python does not simply do 12 + 5 + 23 + 1 it uses the modifier like this:

(((12 + 5) + 23) + 1) = 41
Enter fullscreen mode Exit fullscreen mode

You can see what's happening? It first finishes the item and the previous and keeps doing this for each item.

Again we can use the Python lambda function to make this even easier.

from functools import reduce

input = [12, 5, 23, 1]

result = reduce(lambda a, b: a + b, input)
print(result)

# 41
Enter fullscreen mode Exit fullscreen mode

Thank you for reading, and let's connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Top comments (0)