DEV Community

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

Posted on

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!

Top comments (0)