Technical skill practice

Cumsum in Python: Running Balances with itertools.accumulate

For a cumulative sum in standard-library Python, use itertools.accumulate. It produces successive running values rather than just one final total. An initial value can represent an opening balance, and that initial value is included in the produced sequence.

Start with a small, explicit task

Start a fictional token ledger at 100 and apply changes of -15, +30 and -10. Preserve the balance after each change, including the opening state. These are integer teaching tokens rather than money, and the example requires no NumPy or pandas installation.

Run the complete example

This original example was checked with Python 3.12.14. Save it as python_cumulative_sum.py and run it with Python 3.12. It uses only the standard library. The assertions check the stated results.

Expected output

[100, 85, 115, 105]

change total: 5

closing balance: 105

from itertools import accumulate
opening = 100
changes = [-15, 30, -10]
balances = list(accumulate(changes, initial=opening))
assert balances == [100, 85, 115, 105]
assert len(balances) == len(changes) + 1
assert balances[-1] == opening + sum(changes)
assert list(accumulate([], initial=opening)) == [100]
assert list(accumulate([])) == []
print(balances)
print("change total:", sum(changes))
print("closing balance:", balances[-1])

Explain the result

The sequence begins with 100 before any change. Subtracting 15 gives 85, adding 30 gives 115 and subtracting 10 gives 105. There is one more balance than change because the initial state is retained. If a report needs one row per transaction, deliberately align transaction rows with balances[1:] rather than silently shifting the numbers.

sum(changes) returns 5, which is the net change and not the closing balance. Adding the opening state produces 105. The empty checks distinguish no changes with an opening state from no changes without one. Materializing the iterator is useful for this small report; a streaming consumer can process running values directly.

Avoid these mistakes

Do not insert the opening balance both into the input changes and into initial, which would count it twice. Choose numeric types appropriate to your own domain; this exact integer exercise does not validate floating-point financial arithmetic or a third-party library’s missing-value behavior.

Questions, answered

Is cumsum the same as sum?

No. The running sequence shows each intermediate state; sum produces one total.

Why is the result one item longer?

The chosen initial=100 is itself the first emitted balance.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.