Content · Programming · Python

Python itertools.accumulate() Function: Usage and Examples

Compute running totals or apply another cumulative operation.

2 views Published Oct 17, 2026 Updated Oct 18, 2026 Admin

Compute running totals or apply another cumulative operation.

What You Will Learn


accumulate(iterable, function=None, *, initial=None) defaults to addition; the optional function combines the previous accumulator and next item. The initial argument adds a starting output element.

Many iterator tools are lazy. Creating the iterator does not necessarily perform the work; advancing it can consume the original source.

Step-by-Step Example


The example below makes the behavior visible with small input values that you can change safely.

from itertools import accumulate
print(list(accumulate([3, 5, 2])))
print(list(accumulate([2, 3, 4], lambda left, right: left * right)))

How the Example Works


  • The imports provide the standard-library tools used in the demonstration: itertools.
  • The print() calls make the return values or state visible so you can compare them with the explanation and check your prediction.

Expected output from the example:

[3, 8, 10]
[2, 6, 24]

Another Example: Compare the Results


Try a second input and compare it with the first. Notice whether the result changes in type, value, order, or number of items.

from itertools import accumulate
print(list(accumulate([2, 3, 5], initial=10)))

Expected output:

[10, 12, 15, 20]

When You Would Use This


This pattern is useful in readers for CSV files, event streams, or paginated API results, where collecting everything in memory is unnecessary. Because iterator state advances when values are consumed, decide whether you need a reusable collection or a one-time pass. Keep files and connections open until their lazy consumers finish.

Practice: Modify the Code


Track a daily running budget balance.

Verify the changed output against the behavior described above, including the relevant invalid or boundary case.

For complete parameters and version details, consult the official Python documentation.

Common Beginner Mistakes


  • Using accumulate() to request only a final total when sum() would be simpler.
  • Consuming a one-pass iterator during an earlier check and assuming the same values remain available.

Key Takeaways


  • Compute running totals or apply another cumulative operation.
  • accumulate(iterable, function=None, *, initial=None) defaults to addition; the optional function combines the previous accumulator and next item.
  • Apply this operation only after checking the assumptions and input conditions shown in the example.
Share this resourceSend this page to someone who may find it useful.