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 execution and performance monitoring
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    sys.monitoring: Low-Overhead Instrumentation

    Learn Python sys.monitoring for low-overhead instrumentation with selective events, callbacks, tooling, and safe observability.

    Ler mais

    Tempo de leitura: 5 minutos
    03/09/2026
    Software developer organizing object data with Python operator.attrgetter
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    operator.attrgetter: Sort Objects by Attributes

    Learn Python operator.attrgetter to sort, group, and transform objects by simple or nested attributes with clearer reusable code.

    Ler mais

    Tempo de leitura: 4 minutos
    02/09/2026
    Asynchronous programming with Python asyncio.Runner
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    asyncio.Runner: Reuse the Event Loop Safely

    Learn Python asyncio.Runner to reuse an event loop, control context, signals, debug mode, cancellation, and safe asynchronous shutdown.

    Ler mais

    Tempo de leitura: 6 minutos
    02/09/2026
    Binary data compression with Zstandard in Python
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    compression.zstd: Zstandard Streams and Dictionaries

    Learn Python compression.zstd for Zstandard compression, streaming, dictionaries, safe limits, testing, and production workflows.

    Ler mais

    Tempo de leitura: 6 minutos
    01/09/2026
    Python application packaged as an executable zipapp archive
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    Python zipapp: Build Executable Apps

    Learn Python zipapp to package applications as executable pyz archives, include dependencies, and distribute tools safely.

    Ler mais

    Tempo de leitura: 5 minutos
    01/09/2026
    Python code used to compose functions with functools.Placeholder
    Advanced Python
    Foto de perfil de Leandro Hirt da Academify

    functools.Placeholder: Positional Gaps in partial

    Learn Python functools.Placeholder to leave positional gaps in partial functions and build clearer reusable functional APIs.

    Ler mais

    Tempo de leitura: 5 minutos
    31/08/2026