Python: Include the opening balance in itertools.accumulate
accumulate(initial=...) yields the initial value before consuming the first input. A running-balance report therefore has one more balance than transactions, including a useful result when there are no transactions.
Tested on Linux with Python 3.12.14. Use Python 3.12 or newer. The example uses only the standard library and requires no network access.
Run the example
Save this as opening_balance_demo.py in an empty working directory:
from itertools import accumulate
changes = [25, -40, 10]
balances = list(accumulate(changes, initial=100))
print("Balances:", balances)
print("Count:", len(balances))
print("No changes:", list(accumulate([], initial=100)))
print("Opening:", balances[0])
for change, balance in zip(changes, balances[1:], strict=True):
print(f"Change {change:+d}: balance {balance}")Run it without -O so any assertions remain enabled:
python3 opening_balance_demo.pyCaptured output:
Balances: [100, 125, 85, 95]
Count: 4
No changes: [100]
Opening: 100
Change +25: balance 125
Change -40: balance 85
Change +10: balance 95Pair transactions with balances[1:]; pairing them with the whole balance list would associate the first change with the opening balance. The strict zip checks that every change has a corresponding resulting balance.
Limits and cleanup
The example uses integer units and materializes a small report. accumulate() itself is lazy, so a large stream can be processed incrementally. A non-None initial value is emitted; initial=None has the default behavior and does not add a leading None.
After testing, remove the example script from its working directory:
rm -- opening_balance_demo.pyReference
Acknowledgements
This post was created with assistance from AI.