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.
Submitted by Shivang Yadav, on April 08, 2021
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.
Program to find the cumulative sum of elements of the list,
In this problem, we will take the list as input from the user. Then print the cumulative sum of elements of the list.
Example:
Input:
[1, 7, 3, 5, 2, 9]
Output:
[1, 8, 11, 16, 18, 27]
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.
Program to find the cumulative sum of elements in 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:
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 »