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
Python Program to Find the Cumulative Sum of a List where the ith Element is the Sum of the First i+1 Elements From The Original List
When it is required to find the cumulative sum of a list where the ith element is the sum of the first i+1 elements from the original list, we can use different approaches. The cumulative sum creates a new list where each element represents the running total up to that position.
Method 1: Using List Comprehension
This approach uses list comprehension with slicing to calculate cumulative sums ?
def cumulative_sum(my_list):
cumulative_list = []
my_length = len(my_list)
cumulative_list = [sum(my_list[0:x:1]) for x in range(1, my_length+1)]
return cumulative_list
my_list = [10, 20, 25, 30, 40, 50]
print("The list is :")
print(my_list)
print("The cumulative sum is :")
print(cumulative_sum(my_list))
The list is : [10, 20, 25, 30, 40, 50] The cumulative sum is : [10, 30, 55, 85, 125, 175]
Method 2: Using itertools.accumulate()
Python's built-in accumulate() function provides an efficient way to calculate cumulative sums ?
import itertools
my_list = [10, 20, 25, 30, 40, 50]
cumulative_sum = list(itertools.accumulate(my_list))
print("The list is :")
print(my_list)
print("The cumulative sum is :")
print(cumulative_sum)
The list is : [10, 20, 25, 30, 40, 50] The cumulative sum is : [10, 30, 55, 85, 125, 175]
Method 3: Using Simple Loop
A straightforward approach using a loop to build the cumulative sum step by step ?
def cumulative_sum_loop(my_list):
cumulative_list = []
running_sum = 0
for num in my_list:
running_sum += num
cumulative_list.append(running_sum)
return cumulative_list
my_list = [10, 20, 25, 30, 40, 50]
print("The list is :")
print(my_list)
print("The cumulative sum is :")
print(cumulative_sum_loop(my_list))
The list is : [10, 20, 25, 30, 40, 50] The cumulative sum is : [10, 30, 55, 85, 125, 175]
Comparison
| Method | Time Complexity | Best For |
|---|---|---|
| List Comprehension | O(n²) | Short, readable code |
| itertools.accumulate() | O(n) | Built-in efficiency |
| Simple Loop | O(n) | Understanding the logic |
How It Works
The cumulative sum calculation works as follows:
Position 0: Sum of first 1 element = 10
Position 1: Sum of first 2 elements = 10 + 20 = 30
Position 2: Sum of first 3 elements = 10 + 20 + 25 = 55
Position 3: Sum of first 4 elements = 10 + 20 + 25 + 30 = 85
Conclusion
Use itertools.accumulate() for the most efficient cumulative sum calculation. For learning purposes, the simple loop method best demonstrates the underlying logic. List comprehension offers concise syntax but with higher time complexity.
