Python itertools.accumulate() Function



The Python itertools.accumulate() function is used to create an iterator that returns accumulated sums or results of a specified binary function applied to the elements of an iterable. This function is commonly used for cumulative summation or custom accumulation operations.

By default, it performs cumulative summation unless a custom function is provided.

Syntax

Following is the syntax of the Python itertools.accumulate() function −

itertools.accumulate(iterable, func=None)

Parameters

This function accepts the following parameters −

  • iterable: The input sequence whose elements will be accumulated.
  • func (optional): A binary function specifying how the accumulation should be performed. If not specified, cumulative summation is used by default.

Return Value

This function returns an iterator that yields accumulated values of the given iterable.

Example 1

Following is an example of the Python itertools.accumulate() function. Here, we compute the cumulative sum of a list of numbers −

import itertools

numbers = [1, 2, 3, 4, 5]
cumulative_sum = itertools.accumulate(numbers)
for num in cumulative_sum:
   print(num)

Following is the output of the above code −

1
3
6
10
15

Example 2

Here, we use itertools.accumulate() function with the multiplication operator to compute a cumulative product −

import itertools
import operator

numbers = [1, 2, 3, 4, 5]
cumulative_product = itertools.accumulate(numbers, operator.mul)
for num in cumulative_product:
   print(num)

Output of the above code is as follows −

1
2
6
24
120

Example 3

Now, we use itertools.accumulate() function with a custom function to compute the maximum encountered value so far in a list −

import itertools

numbers = [3, 1, 4, 1, 5, 9, 2]
cumulative_max = itertools.accumulate(numbers, max)
for num in cumulative_max:
   print(num)

The result obtained is as shown below −

3
3
4
4
5
9
9

Example 4

The itertools.accumulate() function can also be used to track the running total of a sequence of floating-point values.

Here, we calculate the cumulative sum of a list of decimal values −

import itertools

decimals = [0.5, 1.2, 3.8, 2.5, 4.1]
cumulative_sum = itertools.accumulate(decimals)
for num in cumulative_sum:
   print(num)

The result produced is as follows −

0.5
1.7
5.5
8.0
12.1
python_modules.htm
Advertisements