Member-only story
Reduce() vs Accumulate() in Python
Learn about functools.reduce( ) and itertools.accumulate( ) in python.

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])

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:

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.