Open In App

Python program to find Cumulative sum of a list

Last Updated : 02 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

Calculating the cumulative sum of a list means finding the running total of the elements as we move through the list. In this article, we will explore How to find the cumulative sum of a list.

Using itertools.accumulate()

This is the most efficient method for calculating cumulative sums. itertools module in Python has a built-in function called accumulate() that automatically calculates the cumulative sum of the elements in a list.

Python
import itertools

l = [1, 2, 3, 4]

# Calculate the cumulative sum using itertools.accumulate
cumulative_sum = list(itertools.accumulate(l))
print(cumulative_sum)

Output
[1, 3, 6, 10]

Other ways that we can use to find cumulative sum of a list are:

Using numpy.cumsum()

numpy provides a function called cumsum() to calculate the cumulative sum very efficiently. This method is similar to itertools.accumulate() but is optimized for numerical arrays, making it extremely fast for large datasets.

Python
import numpy as np

l = [1, 2, 3, 4]

# Calculate the cumulative sum using numpy's cumsum function
cumulative_sum = np.cumsum(l)

print(cumulative_sum)

Output
[ 1  3  6 10]

Using Loop

This is the most straightforward method to calculate the cumulative sum. We can manually loop through the list, keep a running total, and append the sum after each step.

Python
l = [1, 2, 3, 4]

total = 0
cumulative_sum = []
for num in l:
  
  # Add the current number to the running total
    total += num  
    
    # Store the running total in the result list
    cumulative_sum.append(total)  
print(cumulative_sum)

Output
[1, 3, 6, 10]

Using List Comprehension

List comprehension is a more compact and Pythonic way to calculate the cumulative sum. Inside the list comprehension we use the := operator (known as the “walrus operator”) to update the total variable and immediately use the updated value in the next iteration.

Python
l = [1, 2, 3, 4]

# List comprehension with an updated total
cumulative_sum =  [sum(l[:i+1]) for i in range(len(l))]
print(cumulative_sum)

Output
[1, 3, 6, 10]

Using a Generator

A generator is a function that yields one result at a time, instead of returning a complete list. This can be more memory-efficient, especially when dealing with large datasets, as it doesn’t store the entire list of results in memory.

Python
def cumulative_sum_generator(l):
    total = 0
    for num in l:
      
       # Update the running total
        total += num 
        
        # Yield the cumulative sum for each element
        yield total  

l = [1, 2, 3, 4]
cumulative_sum = list(cumulative_sum_generator(l))  
print(cumulative_sum)

Output
[1, 3, 6, 10]

Explanation:

  • Here, the cumulative_sum_generator() function is a generator that calculates and yields the cumulative sum as we iterate through the list.
  • The yield keyword returns the cumulative sum for each element without storing the entire list of results in memory.


Next Article

Similar Reads