Python program to find Cumulative sum of a list

• Difficulty Level : Basic
• Last Updated : 29 Dec, 2022

The problem statement asks to produce a new list whose i^{th} element will be equal to the sum of the (i + 1) elements.

Examples :

Input : list = [10, 20, 30, 40, 50]
Output : [10, 30, 60, 100, 150]

Input : list = [4, 10, 15, 18, 20]
Output : [4, 14, 29, 47, 67]

Approach 1 :
We will use the concept of list comprehension and list slicing to get the cumulative sum of the list. The list comprehension has been used to access each element from the list and slicing has been done to access the elements from start to the i+1 element. We have used the sum() method to sum up the elements of the list from start to i+1.
Below is the implementation of the above approach :

Python3

 # Python code to get the Cumulative sum of a listdef Cumulative(lists):    cu_list = []    length = len(lists)    cu_list = [sum(lists[0:x:1]) for x in range(0, length+1)]    return cu_list[1:] # Driver Codelists = [10, 20, 30, 40, 50]print (Cumulative(lists))

Output

[10, 30, 60, 100, 150]

Approach 2:

Python3

 list=[10,20,30,40,50]new_list=[]j=0for i in range(0,len(list)):    j+=list[i]    new_list.append(j)     print(new_list)#code given by Divyanshu singh

Output

[10, 30, 60, 100, 150]

Time Complexity: O(n)

Auxiliary Space: O(n)

Alternate approach : Use itertools module

One approach that is not mentioned in the provided solution is to use the built-in accumulate() function from the itertools module. This function allows you to perform a cumulative sum of the elements in an iterable, and returns an iterator that produces the cumulative sum at each step.

To use this function, you can pass your list as the first argument, and specify the operator.add function as the second argument, which will be used to perform the cumulative sum. Here is an example of how this can be implemented:

Python3

 from itertools import accumulateimport operator def cumulative_sum(input_list):    # Use the accumulate() function to perform a cumulative sum of the elements in the list    cumulative_sum_iter = accumulate(input_list, operator.add)    # Convert the iterator to a list and return it    return list(cumulative_sum_iter) input_list = [10, 20, 30, 40, 50]output_list = cumulative_sum(input_list)print(output_list)

Output

[10, 30, 60, 100, 150]

My Personal Notes arrow_drop_up