codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Follow publication

Reduce() vs Accumulate() in Python

Learn about functools.reduce( ) and itertools.accumulate( ) in python.

Indhumathy Chelliah
codeburst
Published in
4 min readAug 18, 2020

Photo by Markus Spiske on Unsplash

reduce() vs accumulate

reduce()

The functools module is for higher-order functions. Functions that act on or return other functions. In general, any callable object can be treated as a function for the purposes of this module.

The functools module provides the following function functools.reduce()

functools.reduce()

Apply function of two arguments cumulatively to the items of iterable, from left to right, so as to reduce the iterable to a single value. -python docs

functools.reduce(function, iterable,initializer)

If the optional initializer is present, it is placed before the items of the iterable in the calculation, and serves as a default when the iterable is empty.

If initializer is not given and iterable contains only one item, the first item is returned.

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

Image Source: Author

Example 1: Find the product of the list elements using reduce()

from functools import reduce
num1=[1,2,3,4,5]
num2=reduce(lambda x,y:x*y,num1)
print (num2)#Output:120

Example 2:Find the largest number in the iterable using reduce()

from functools import reduce
num1=[15,12,30,4,5]
num2=reduce(lambda x,y: x if x>y else y,num1)
print (num2)#Output:30

Pictorial representation:

Image Source: Author

Example 3:Using User-defined function in reduce()

from functools import reduce
def sum1(x,y):
return x+y
num1=[15,12,30,4,5]
num2=reduce(sum1,num1)
print (num2)#Output:66

Example 4: Initializer is mentioned.

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Published in codeburst

Bursts of code to power through your day. Web Development articles, tutorials, and news.

Written by Indhumathy Chelliah

Machine Learning | Python |R | Tableau | 1.5 M Views

Responses (2)

Write a response