Python program to find Cumulative sum of a list
Last Updated :
02 Jan, 2025
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.
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)
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)
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)
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)
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)
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.
Similar Reads
Python Program to Find Sum of Array Given an array of integers, find the sum of its elements. Examples: Input : arr[] = {1, 2, 3}Output : 6Explanation: 1 + 2 + 3 = 6This Python program calculates the sum of an array by iterating through each element and adding it to a running total. The sum is then returned. An example usage is provid
4 min read
Python | Pandas Series.cumsum() to find cumulative sum of a Series Pandas Series.cumsum() is used to find Cumulative sum of a series. In cumulative sum, the length of returned series is same as input and every element is equal to sum of all previous elements. Syntax: Series.cumsum(axis=None, skipna=True) Parameters: axis: 0 or 'index' for row wise operation and 1 o
2 min read
Python | Pandas Series.cummin() to find cumulative minimum of a series Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.cummin() is used to find Cumulative minimum of a series. In cumulative m
2 min read
Python | Pandas series.cummax() to find Cumulative maximum of a series Python is a great language for doing data analysis, primarily because of the fantastic ecosystem of data-centric Python packages. Pandas is one of those packages and makes importing and analyzing data much easier. Pandas Series.cummax() is used to find Cumulative maximum of a series. In cumulative m
3 min read
Find sum of elements in List - Python Finding the sum of elements in a list means adding all the values together to get a single total. For example, given a list like [10, 20, 30, 40, 50], you might want to calculate the total sum, which is 150. Let's explore these different methods to do this efficiently.Using sum()sum() function is th
3 min read
Find sum of elements in List - Python Finding the sum of elements in a list means adding all the values together to get a single total. For example, given a list like [10, 20, 30, 40, 50], you might want to calculate the total sum, which is 150. Let's explore these different methods to do this efficiently.Using sum()sum() function is th
3 min read