The question
An array a holds 6 numbers. We want range sums: the total of a[lo:hi], the items from index lo up to, but not including, hi. Example: a[2:5] covers 4, 1, 5.
The plain way walks the range and adds each item: 4, then 5, then 10. That is hi − lo additions per query. With n items and q queries, it can cost about n × q additions.
Build the prefix array
Better: add up once, up front. Build a second array p, where p[i] is the sum of the first i items of a. It starts with p[0] = 0, the sum of no items at all.
Each new slot reuses the one before it: p[i + 1] = p[i] + a[i]. So p[1] = 0 + 3 = 3 and p[2] = 3 + 1 = 4. One addition per slot, never a recount.
Carry on to the end: p = [0, 3, 4, 8, 9, 14, 23]. That took 6 additions for 6 items, so building p costs O(n) time. p has n + 1 slots, and the last one is the total.
One subtraction per query
Now a range sum is one subtraction: sum(a[lo:hi]) = p[hi] − p[lo]. p[5] = 3+1+4+1+5 and p[2] = 3+1. The shared 3+1 cancels, leaving 4+1+5: 14 − 4 = 10.
The same p answers every range. The whole array: p[6] − p[0] = 23 − 0 = 23. This is why p starts with a 0: a range that starts at index 0 still needs a p[lo].
The trade: O(n) time and O(n) extra memory once, then O(1) per query, however long the range. q queries cost about n + q steps instead of n × q. If a changes, p must be rebuilt.
What happens
;; step 1/8 · the-question a = [3, 1, 4, 1, 5, 9] index: 0 1 2 3 4 5 range sum a[lo:hi] = a[lo] + ... + a[hi - 1] a[2:5] = 4 + 1 + 5 = 10 Python slices are half-open: lo is in, hi is out
a[lo:hi] follows Python slicing: it holds the items with index k where lo ≤ k < hi, so a[2:5] is a[2], a[3] and a[4]. That half-open rule is what makes p[hi] − p[lo] come out exactly right, with no ± 1. Python can build the same array for you: list(itertools.accumulate(a, initial=0)) returns [0, 3, 4, 8, 9, 14, 23]. The initial argument was added in Python 3.8.