Python program to find Cumulative sum of a list
Last Updated :
31 Oct, 2025
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.
The itertools module provides a built-in function called accumulate(), which automatically computes cumulative sums.
Python
import itertools
l = [1, 2, 3, 4]
res = list(itertools.accumulate(l))
print(res)
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.
Python
import numpy as np
l = [1, 2, 3, 4]
res = np.cumsum(l)
print(res)
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.
Python
l = [1, 2, 3, 4]
total = 0
res = []
for num in l:
total += num
res.append(total)
print(res)
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.
Python
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.
Python
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)
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].
Related Articles:
Explore
Python Fundamentals
Python Data Structures
Advanced Python
Data Science with Python
Web Development with Python
Python Practice