What is the itertools.accumulate() method in Python?
Overview
itertools is a module in Python that provides functions. These functions help in iterating through iterables.
The accumulate() method in the itertools module returns a new iterator. This consists of the sum of the elements’ accumulation in the iterable or the results of the binary function.
- The binary function should take two arguments.
- If no function is specified, the default function is addition. The number of elements in the input iterable is equal to the number of elements in the output iterable.
- The method takes a keyword argument called
initial. If this argument is specified, the accumulation starts with theinitialvalue. This results in an output iterable with one more element than the input iterable.
Syntax
itertools.accumulate(iterable, func, *, initial=None)
Parameters
iterable: This is the iterable.func: This is the binary function. It is an optional argument.initial: This is the initial value to consider during the start of the iteration. This is an optional argument.
Example
from itertools import accumulatelst = [1,2,3,4,5, 5, 6, 6]print("Originl list - ", lst)print("Sum accumulation - ", list(accumulate(lst)))initial_val = 50print("Sum accumulation with initial value - ", list(accumulate(lst, initial=initial_val)))print("Minimum value accumulation - ", list(accumulate(lst, min)))
Explanation
- Line 1: We import the
accumulatefunction from theitertoolsmodule. - Line 3: We define a list of numbers called
lst. - Line 4: The
lstlist is printed. - Line 5: The
accumulatefunction is invoked withlst. Since nofuncargument is passed toaccumulate, the default addition is performed. - Line 7: An initial value called
initial_valis defined. - Line 8: The
accumulatefunction is invoked withlstandinitial_valas arguments. The output starts with theinitial_valas the first element and then the running sum occurs over the elements of the iterable. - Line 10: Here, we pass the
minbinary function. This finds the minimum of the two given values as thefuncargument to theaccumulatemethod. Hence, the running minimum is calculated.