Python itertools Module : accumulate Function
Accumulate function in itertools module accumulates the iterables based on the function(func) provided to it as an argument. If func is not provided to it then by default it adds the iterables. The function(func) provided to this function should accept two variables and return the result. Accumulate function returns an iterator to the output, so to see all outputs we need to iterate over it. Elements of the input iterable may be any type that can be accepted as arguments to func. If the input iterable is empty, the output iterable will also be empty. There are a number of uses for the func argument. It can be set to min() for a running minimum, max() for a running maximum, or operator.mul() for a running product.
Syntax
itertools.
accumulate
(iterable[,func])
Parameters
iterable : Required. Elements to be accumulated.
func : Optional. Function to accumulate iterables.
Sample Program
#importing itertools module
import itertools
iterables = [1,3,6,2,7,9,3,1,11]
data = itertools.accumulate(iterables)
print(list(data))
iterables = [1,3,6,2,7,8,3,1,11]
data = itertools.accumulate(iterables)
print(list(data))
iterables = [1,3,6,2,7,9,3,1,11]
data = itertools.accumulate(iterables,lambda x,y : x*y)
print(list(data))
def collect(x,y):
z = y.lower()
return x+z+z
iterables = ['A','B','C','D']
data = itertools.accumulate(iterables,collect)
Output
[1, 4, 10, 12, 19, 28, 31, 32, 43] [1, 3, 18, 36, 252, 2268, 6804, 6804, 74844] ['A', 'Abb', 'Abbcc', 'Abbccdd']
Comments