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 elements in list 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
Python program to find the sum of all items in a dictionary The task of finding the sum of all items in a dictionary in Python involves calculating the total of all values stored in a dictionary. For example, given a dictionary {'a': 100, 'b': 200, 'c': 300}, the sum of values would be 100 + 200 + 300 = 600. Using sum()This is the simplest and fastest method
3 min read
Python | Accumulative index summation in tuple list Sometimes, while working with data, we can have a problem in which we need to find accumulative summation of each index in tuples. This problem can have applications in web development and competitive programming domain. Let's discuss certain way in which this problem can be solved. Method 1: Using
8 min read
Python program to find the sum of Characters ascii values in String List Given the string list, the task is to write a Python program to compute the summation value of each character's ASCII value. Examples: Input : test_list = ["geeksforgeeks", "teaches", "discipline"] Output : [133, 61, 100] Explanation : Positional character summed to get required values. Input : test
4 min read
Find Sum and Average of List in Python Our goal is to find sum and average of List in Python. The simplest way to do is by using a built-in method sum() and len(). For example, list of numbers is, [10, 20, 30, 40, 50] the sum is the total of all these numbers and the average is the sum divided by the number of elements in the list.Using
2 min read