A Python Implementation of NumPy Cumsum

You may know the np.cumsum() function from the NumPy library that calculates the cumulative sum of a given NumPy array.

How can we implement this function in Python? Studying this will not only show you how the NumPy cumsum function works, but it’ll also make you a better coder because it contains many important concepts in computer science (such as recursion).

Here’s the NumPy cumsum function in Python code (without using the NumPy library):

def cumsum(l:list):

    if not l:
        return []
    sums = []
    return helper(sums, l[1:])
def helper(sums:list, xs:list):

    if not xs:
        return sums
    s = sums[len(sums) - 1]
    sums.append(s + xs[0])
    if len(xs) > 1:
        return helper(sums, xs[1:])
    return sums
xs = [1]

xs = [1, 3, 3, 2, 5]
# [1, 4, 7, 9, 14]

xs = [1, 1, 1, 2]
# [1, 2, 3, 5]

The functions in this code snippet compute a list of sums from the values of the input list. In the output list at index j there is the sum of sums[j-1] + input[j].

This is done in a recursive way. The cumsum function only starts the recursion by putting the first element of the input list in the first position of the output list and then it starts the recursion with the helper-function by passing the lists sums and xs[1:]. Note that in each recursion step the xs list is shorter because we slice off the first element each time.

With the given input [1, 1, 1, 2] we compute the output [1, 1+1, 1+1+1, 1+1+1+2] = [1, 2, 3, 5].

Where to Go From Here

Want to dive deeper into the ins and outs of the NumPy library? If you have any ambition in data science or machine learning, you should. NumPy is the most important library to learn in the Python ML and data science area!

Read my book “Coffee Break NumPy” to experience a fun way of mastering NumPy—based on the popular puzzle-based learning technique. Everything else in data science will be much easier after you’ve mastered NumPy!

Leave a Comment