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.cumsum is a scan, not a reduction: the output has the same shape as the input. Every partial sum is preserved, unlike a.sum() which collapses the whole array to a single scalar.
  • Position i of the output equals a[:i+1].sum() — the sum of the first i+1 elements.
  • np.cumsum also accepts an axis argument for 2-D arrays: axis=0 produces running column sums, axis=1 produces running row sums.
  • For the equivalent pure-Python pattern see running-total in the python-data-basics book.
  • Shape, dtype, and values are shown explicitly here because ndarray.__repr__ output varies with NumPy version and print options.