Python program to find Cumulative sum of a list

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 :
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 implementation of above approach :





# Python code to get the Cumulative sum of a list 
def 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 Code 
lists = [10, 20, 30, 40, 50
print (Cumulative(lists)) 


Output :

[10, 30, 60, 100, 150]
My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using or mail your article to See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.

Improved By : kaushikkakdey