Reductions
Cumulative Sum
Build a running-total list from a 6-element input by accumulating a counter
inside a loop. Each step appends the current total to running. The replay
shows both total and running growing together, making the running-total
pattern explicit before the single-call NumPy version.
By hand
With NumPy
np.cumsum(a) computes the cumulative sum in one call, returning an array of
the same length as the input where position i holds the sum of all elements
up to and including index i.
naive.py
values = [1, 2, 3, 4, 5, 6]
running = []
total = 0
for v in values:
total += v
running.append(total)
print('RESULT:', running)
library.py
import numpy as np
values = [1, 2, 3, 4, 5, 6]
a = np.array(values)
result = np.cumsum(a)
print('shape:', result.shape)
print('dtype:', result.dtype)
print('values:', result.tolist())
print('RESULT:', result.tolist())
shape: (6,)
dtype: int64
values: [1, 3, 6, 10, 15, 21]
RESULT: [1, 3, 6, 10, 15, 21]
Implementation notes
np.cumsumis a scan, not a reduction: the output has the same shape as the input. Every partial sum is preserved, unlikea.sum()which collapses the whole array to a single scalar.- Position
iof the output equalsa[:i+1].sum()— the sum of the firsti+1elements. np.cumsumalso accepts anaxisargument for 2-D arrays:axis=0produces running column sums,axis=1produces running row sums.- For the equivalent pure-Python pattern see
running-totalin the python-data-basics book. - Shape, dtype, and values are shown explicitly here because
ndarray.__repr__output varies with NumPy version and print options.