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

    A developer typing code on a laptop with a Python book beside in an office.
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    itertools.groupby: Group Sorted Data Correctly

    Learn Python itertools.groupby for ordered data, streaming aggregation, shared iterators, object keys, and correct grouping behavior.

    Ler mais

    Tempo de leitura: 2 minutos
    30/08/2026
    Close-up of hands typing on a laptop keyboard, Python book in sight, coding in progress.
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    contextlib.chdir: Risks of Changing Directories

    Learn Python contextlib.chdir, its global-state and concurrency risks, and when pathlib or subprocess cwd is the safer design.

    Ler mais

    Tempo de leitura: 3 minutos
    30/08/2026
    A person typing on a laptop with a Python programming book visible, capturing technology and learning.
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    Python nullcontext: Optional Contexts

    Use Python nullcontext to unify optional files, locks, transactions, sessions, and borrowed resources without duplicate branches.

    Ler mais

    Tempo de leitura: 4 minutos
    30/08/2026
    Detailed shot of a Jungle Carpet Python (Morelia spilota cheynei) in its natural habitat.
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    contextlib.aclosing: Close Async Generators Safely

    Learn Python contextlib.aclosing to close async generators safely after break, return, exceptions, cancellation, and partial consumption.

    Ler mais

    Tempo de leitura: 5 minutos
    30/08/2026
    Detailed close-up texture of a snake's patterned skin showcasing natural patterns and scales.
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    weakref.finalize: Cleanup Without Retaining Objects

    Learn Python weakref.finalize for safe fallback cleanup without retaining objects, including alive, detach, shutdown, and explicit close.

    Ler mais

    Tempo de leitura: 5 minutos
    30/08/2026
    Close-up view of a computer screen displaying code in a software development environment.
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    SimpleNamespace: Lightweight Attribute Objects

    Learn Python SimpleNamespace for lightweight attribute objects, dictionary conversion, copying, JSON, and choosing better typed models.

    Ler mais

    Tempo de leitura: 5 minutos
    29/08/2026