ADVERTISEMENT
ADVERTISEMENT

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 »



ADVERTISEMENT
ADVERTISEMENT


Comments and Discussions!



ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT
ADVERTISEMENT

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.