- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Write a program to form a cumulative sum list in Python
The cumulative sum till ith element refers to the total sum from 0th to ith element.
The program statement is to form a new list from a given list. The ith element in the new list will be the cumulative sum from 0 to ith element in the given list.
For example,
Input
[10,20,30,40,50]
Output
[10,30,60,100,150]
Input
[1,2,3,4,5]
Output
[1,3,6,10,15]
Following is a program to form a cumulative sum list using the input list −
The input list is passed to the function cumSum() which returns the cumulative sum list.
We declare an empty list cum_list to which we will append elements to form the cumulative sum list.
Initialize a sum variable sm=0.
Start iterating over the input list, with each iteration we increment the sum value to previous value+ the current element.
On each iteration, the sum value is appended to the cum_list.
Thus, on ith iteration, the sum variable will contain sum till the ith element(included), which is then appended to the cum_list.
After iterating through the whole list, the cum_list is returned.
Example
def cumSum(s): sm=0 cum_list=[] for i in s: sm=sm+i cum_list.append(sm) return cum_list a=[10,20,30,40,50] print(cumSum(a))
Output
[10, 30, 60, 100, 150]