Blog this post

Suppose we want to generate the running sum series r formed by sums of n consecutive elements taken from a series s. For example, to sum consecutive pairs taken from the first 6 integers:

>>> n = 2
>>> s = 0, 1, 2, 3, 4, 5
>>> running_sum(s, 2) [1, 3, 5, 7, 9]

One approach would be to combine the sum built-in function with list slices and comprehensions.

>>> def running_sum(s, n): ...  return [sum(s[lo:lo + n]) for lo in range(len(s) - n + 1)] ...
>>> running_sum([0, 1, 2, 3, 4, 5], 2) [1, 3, 5, 7, 9]

This is fine if:

s supports slice access (i.e. s[lo:hi] doesn’t raise a TypeError) n isn’t too big

With just a little extra thought we can address all these issues.