DEV Community

Cover image for reduce function in Python3+
Oscar Eduardo Bolaños Ocampo
Oscar Eduardo Bolaños Ocampo

Posted on

2

reduce function in Python3+

The reduce function is part of functools module of Python, you need two arguments for used, one a function and two a iterable. The reduce function applies the first argument to each element of iterable cumulatively. This function is equivalent to:

def reduce(function, iterable, initializer=None):
    it = iter(iterable)
    if initializer is None:
        value = next(it)
    else:
        value = initializer
    for element in it:
        value = function(value, element)
    return value
Enter fullscreen mode Exit fullscreen mode

This is the Python documentation example:

from functools import reduce

output = reduce(lambda x, y: x+y, [1, 2, 3, 4, 5]) 
print(output)

[1]: 15
Enter fullscreen mode Exit fullscreen mode

That is useful in some cases like in a math series:

from functools import reduce

elements = range(1, 36)
reduce(lambda x, y: x+(1/y**2), elements)

[1]: 1.616766914907197

elements = range(1, 360)
reduce(lambda x, y: x+(1/y**2), elements)

[2]: 1.642152427473518

elements = range(1, 3600)
reduce(lambda x, y: x+(1/y**2), elements)

[3]: 1.6446562504866367
Enter fullscreen mode Exit fullscreen mode

It is not the best way to calculate π**2 / 6, but it is an example of how to use the reduce function.

π**2 / 6
from math import pi

pi**2/6

[1]: 1.6449340668482264
Enter fullscreen mode Exit fullscreen mode

;P


Can be useful for other applications but I love math so enjoy it! Anyway if you have doubts, comments, or corrections about I would like to receive feedback ♥️

Thanks for reading!

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Billboard image

Create up to 10 Postgres Databases on Neon's free plan.

If you're starting a new project, Neon has got your databases covered. No credit cards. No trials. No getting in your way.

Try Neon for Free →

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay