1def lsum(a):2 total = 03 for x in a:4 total += x5 return totala[0]4a[1]1a[2]5a[3]2rsumi=0i=1i=2i=3i=41def rsum(a, i=0):2 if i == len(a):3 return 04 return a[i] + rsum(a, i + 1)lsumtotalmax1000framespeakreturned
Frame blocks: one per call still running, stacked on its call stackThe ring: the peak, the most frames in memory at onceA flying block: a new call getting its frameThe recursive function rsum on the front card; every call that is still waiting keeps one frame block on its call stack, so a list of n numbers needs n + 1 frames at the peak. The ring marks the peak: auxiliary space is the most extra memory in use at once, Θ(n) for rsum. The loop lsum needs one frame for any n: Θ(1). CPython stops recursion at 1000 nested calls by default.

What counts as space

  1. Time counts steps; space counts memory. The list a = [4, 1, 5, 2] is the input, n = 4 numbers. It is in memory before any call, so we count only the extra memory a function makes: its auxiliary space.

The call stack

Proving the cost

What happens

;; step 1/8 · extra-space
a = [4, 1, 5, 2]      n = 4

total space     = input + auxiliary
auxiliary space = extra memory the function
                  uses while it runs

the input is the same for every algorithm,
so space cost counts only the auxiliary part

Cost model: one frame counts as one unit of memory. The byte size of a real frame depends on the Python version, but it is the same for every call of rsum, so counting frames gives the right growth rate. Freed memory is used again by the next call, so space is measured at the busiest moment. For a recursive function that is the depth of the deepest chain of waiting calls.