Home »
Python »
Python Programs
Python program to find the cumulative sum of elements of a list
Here, we will take a list of input from the user and return the list of cumulative sum of elements of the list.
By Shivang Yadav Last updated : September 18, 2023
Python programming language is a high-level and object-oriented programming language. Python is an easy to learn, powerful high-level programming language. It has a simple but effective approach to object-oriented programming.
List is a sequence data type. It is mutable as its values in the list can be modified. It is a collection of ordered sets of values enclosed in square brackets [].
Cumulative Sum is the sequence of partial sum i.e. the sum till current index.
Problem statement
In this problem, we will take the list as input from the user. Then print the cumulative sum of elements of the list.
Example
Consider the below example with sample input and output:
Input:
[1, 7, 3, 5, 2, 9]
Output:
[1, 8, 11, 16, 18, 27]
Finding the cumulative sum of elements of a list
To perform the task, we need to iterate over the list and find the sum till the current index and, store it to a list and then print it.
Python program to find the cumulative sum of elements of a list
# Python program to find cumulative sum
# of elements of list
# Getting list from user
myList = []
length = int(input("Enter number of elements : "))
for i in range(0, length):
value = int(input())
myList.append(value)
# finding cumulative sum of elements
cumList = []
sumVal = 0
for x in myList:
sumVal += x
cumList.append(sumVal)
# Printing lists
print("Entered List ", myList)
print("Cumulative sum List ", cumList)
Output
The output of the above program is:
Enter number of elements : 5
1
7
3
5
2
Entered List [1, 7, 3, 5, 2]
Cumulative sum List [1, 8, 11, 16, 18]
Python List Programs »