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 the initial value. 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 accumulate
lst = [1,2,3,4,5, 5, 6, 6]
print("Originl list - ", lst)
print("Sum accumulation - ", list(accumulate(lst)))
initial_val = 50
print("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 accumulate function from the itertools module.
  • Line 3: We define a list of numbers called lst.
  • Line 4: The lst list is printed.
  • Line 5: The accumulate function is invoked with lst. Since no func argument is passed to accumulate, the default addition is performed.
  • Line 7: An initial value called initial_val is defined.
  • Line 8: The accumulate function is invoked with lst and initial_val as arguments. The output starts with the initial_val as the first element and then the running sum occurs over the elements of the iterable.
  • Line 10: Here, we pass the min binary function. This finds the minimum of the two given values as the func argument to the accumulate method. Hence, the running minimum is calculated.

Free Resources