Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Write a program to form a cumulative sum list in Python
The cumulative sum till ith element refers to the total sum from 0th to ith element. We need to form a new list where each element represents the running total up to that position.
For example, if we have [10, 20, 30, 40, 50], the cumulative sum list would be [10, 30, 60, 100, 150].
Example Input and Output
Example 1
Input: [10, 20, 30, 40, 50]
Output: [10, 30, 60, 100, 150]
Example 2
Input: [1, 2, 3, 4, 5]
Output: [1, 3, 6, 10, 15]
Using a Custom Function
We can create a function that iterates through the list and maintains a running sum ?
def cumSum(numbers):
sm = 0
cum_list = []
for i in numbers:
sm = sm + i
cum_list.append(sm)
return cum_list
a = [10, 20, 30, 40, 50]
print("Original list:", a)
print("Cumulative sum:", cumSum(a))
b = [1, 2, 3, 4, 5]
print("Original list:", b)
print("Cumulative sum:", cumSum(b))
Original list: [10, 20, 30, 40, 50] Cumulative sum: [10, 30, 60, 100, 150] Original list: [1, 2, 3, 4, 5] Cumulative sum: [1, 3, 6, 10, 15]
Using List Comprehension
A more compact approach using list comprehension with sum() and slicing ?
numbers = [10, 20, 30, 40, 50]
cumulative = [sum(numbers[:i+1]) for i in range(len(numbers))]
print("Original list:", numbers)
print("Cumulative sum:", cumulative)
Original list: [10, 20, 30, 40, 50] Cumulative sum: [10, 30, 60, 100, 150]
Using itertools.accumulate()
Python's itertools.accumulate() function provides a built-in solution ?
import itertools
numbers = [10, 20, 30, 40, 50]
cumulative = list(itertools.accumulate(numbers))
print("Original list:", numbers)
print("Cumulative sum:", cumulative)
Original list: [10, 20, 30, 40, 50] Cumulative sum: [10, 30, 60, 100, 150]
How It Works
The algorithm maintains a running sum:
Initialize an empty result list and sum variable to 0
Iterate through each element in the input list
Add the current element to the running sum
Append the running sum to the result list
Return the cumulative sum list
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| Custom Function | O(n) | O(n) | High |
| List Comprehension | O(n²) | O(n) | Medium |
| itertools.accumulate() | O(n) | O(n) | High |
Conclusion
Use itertools.accumulate() for the most efficient and readable solution. The custom function approach is best for learning the underlying logic, while list comprehension offers a compact but less efficient alternative.
