Subscribe

Python reduce() function

✍️

How to use the reduce() function in Python

6 Jun, 2021 · 2 min read

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)

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

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

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

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

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Speedtest your connection in Python

21 Jun, 2021 · 2 min read

Speedtest your connection in Python

F-strings in Python

7 Jun, 2021 · 2 min read

F-strings in Python

Join 2099 devs and subscribe to my newsletter