itertools.accumulate: Running Sums and State

Published on: August 30, 2026
Reading time: 2 minutes
Detailed close-up of yellow and white albino python scales, capturing texture and pattern.

itertools.accumulate() yields accumulated results while traversing an iterable. By default it creates running sums, but it can also use multiplication, maximum, minimum, or a custom state transition. Because the result is an iterator, it fits streaming pipelines and large datasets.

This guide covers running totals, initial, operator functions, balances, running records, averages, and mutable-state pitfalls.

Running sums

from itertools import accumulate

values = [10, 5, -2, 8]
print(list(accumulate(values)))
# [10, 15, 13, 21]

Each output combines the previous accumulated value with the next item.

Initial value

print(list(accumulate([5, 7, 3], initial=100)))
# [100, 105, 112, 115]

The initial value is emitted first, which is useful for account balances, positions, and state before the first event.

Running products

from operator import mul

print(list(accumulate([2, 3, 4], mul)))
# [2, 6, 24]

Running maximum

temperatures = [18, 20, 19, 24, 22]
print(list(accumulate(temperatures, max)))
# [18, 20, 20, 24, 24]

Balances after transactions

transactions = [200, -50, -25, 100]
balances = accumulate(transactions, initial=1000)
for balance in balances:
    print(balance)

Custom transition

def clamp_balance(current, change):
    return max(0, current + change)

states = accumulate([-3, 8, -20, 5], clamp_balance, initial=10)

The function receives the current accumulated state and the next input item, then returns the next state.

Lazy processing

accumulate computes values only when requested. Combine it with islice, filters, or other itertools functions.

from itertools import accumulate, islice

first_states = islice(accumulate(events(), update_state), 100)

Running averages

def update(state, value):
    total, count = state
    return total + value, count + 1

states = accumulate([10, 20, 15], update, initial=(0, 0))
averages = [total / count for total, count in states if count]

Prefer immutable state

If a transition mutates and returns the same list or dictionary, yielded results may all reference one object. Prefer tuples, frozen dataclasses, or explicit copies.

accumulate versus sum

sum returns only the final total. accumulate exposes every intermediate result.

accumulate versus reduce

functools.reduce also combines values but returns one final result. Choose accumulate when the full progression matters.

Numerical precision

Long floating-point sums may accumulate rounding error. Use decimal.Decimal for decimal business values. math.fsum can improve a final floating-point total, although it does not yield intermediate states.

Common mistakes

  • Forgetting that initial adds one output.
  • Reversing accumulator-function arguments.
  • Mutating the same state object.
  • Converting an infinite result to a list.
  • Expecting a scalar instead of an iterator.

Keep transition functions pure, use small immutable states, document the initial value, and consume the iterator incrementally. See the internal guides to Python itertools, groupby, and pairwise.

Conclusion

itertools.accumulate is a compact tool for running totals and state transitions. Its lazy design supports low-memory pipelines, while custom functions extend it far beyond addition.

External sources

Share:

Facebook
WhatsApp
Twitter
LinkedIn

Article content

    Related articles

    Python code on a laptop for filtering None values
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    operator.is_none: Filter None Without Losing Falsy

    Learn operator.is_none and is_not_none to filter None values without removing valid falsy data in Python.

    Ler mais

    Tempo de leitura: 4 minutos
    23/10/2026
    Python code on a laptop for creating dynamic dataclasses
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    make_dataclass decorator: Transform Dataclasses

    Learn how the make_dataclass decorator parameter validates, registers, and transforms dynamic dataclasses safely in Python.

    Ler mais

    Tempo de leitura: 5 minutos
    23/10/2026
    Code and XML structure for canonicalization with Python
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    ElementTree canonicalize: Normalize XML in Python

    Learn Python ElementTree canonicalize for stable XML comparisons, hashes, namespaces, comments, and signature preparation.

    Ler mais

    Tempo de leitura: 5 minutos
    22/10/2026
    Python programming code displayed on a screen
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    T-strings and templatelib: Structured Interpolation

    Learn Python t-strings and string.templatelib for structured interpolation, safer renderers, logging, and custom processing.

    Ler mais

    Tempo de leitura: 5 minutos
    22/10/2026
    SQLite database and Python code for selective iterdump export
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    SQLite iterdump: Create Selective Dumps in Python

    Learn sqlite3.Connection.iterdump filters for selective SQLite dumps, dependency checks, validation, and safer restoration.

    Ler mais

    Tempo de leitura: 4 minutos
    21/10/2026
    Code and files representing Python data compression
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    compression.zstd: Fast Zstandard in Python

    Learn Python compression.zstd for fast file and data compression, streaming, integrity checks, and safe decompression.

    Ler mais

    Tempo de leitura: 7 minutos
    21/10/2026