Python program to find Cumulative sum of a list
Given a list of numbers, the task is to find the cumulative sum (also known as the running total) where each element in the output represents the sum of all elements up to that position in the original list.
Example:
Input: [1, 2, 3, 4]
Output: [1, 3, 6, 10]
In this article, we will explore various methods to find the cumulative sum of a list in Python.
Using itertools.accumulate()
The itertools module provides a built-in function called accumulate(), which automatically computes cumulative sums.
import itertools
l = [1, 2, 3, 4]
res = list(itertools.accumulate(l))
print(res)
Output
[1, 3, 6, 10]
Explanation: itertools.accumulate(l) returns an iterator that generates the running (cumulative) sum of the list elements.
Using numpy.cumsum()
NumPy provides a highly optimized method called cumsum(). It returns the cumulative sum of array elements efficiently, making it ideal for numerical and large datasets.
import numpy as np
l = [1, 2, 3, 4]
res = np.cumsum(l)
print(res)
Output
[ 1 3 6 10]
Explanation: np.cumsum() NumPy function that computes the cumulative (running) sum of array elements.
Using a Loop
The traditional way to compute cumulative sums is by using a simple for loop and maintaining a running total.
l = [1, 2, 3, 4]
total = 0
res = []
for num in l:
total += num
res.append(total)
print(res)
Output
[1, 3, 6, 10]
Explanation:
- Initialize total = 0 and an empty list res.
- Loop through each number, add it to total, and append total to the list.
Using List Comprehension
A list comprehension can be used to achieve the same result more compactly.
l = [1, 2, 3, 4]
res = [sum(l[:i+1]) for i in range(len(l))]
print(res)
Explanation:
- [sum(l[:i+1]) for i in range(len(l))]: For each index i, sum all elements from start up to i.
- Creates a list of cumulative sums in one line.
Using a Generator
A generator yields cumulative sums one by one, instead of returning the entire list at once.
def cum_sum(lst):
s = 0
for i in lst:
s += i
yield s
l = [1, 2, 3, 4]
s1 = list(cum_sum(l))
print(s1)
Output
[1, 3, 6, 10]
Explanation:
- Loops through the list, updating a running total.
- yield returns each cumulative sum on-the-fly.
- Converting with list() produces the full cumulative sum list: [1, 3, 6, 10].