
- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
Python Program to Find the Cumulative Sum of a List where the ith Element is the Sum of the First i+1 Elements From The Original List
When it is required to find the sum of a list where the specific element is sum of first few elements, a method is defined, that takes list as parameter. It uses list comprehension to find the cumulative sum.
Below is the demonstration of the same −
Example
def cumulative_sum(my_list): cumulative_list = [] my_length = len(my_list) cumulative_list = [sum(my_list[0:x:1]) for x in range(0, my_length+1)] return cumulative_list[1:] my_list = [10, 20, 25, 30, 40, 50] print("The list is :") print(my_list) print("The cumulative sum is :") print (cumulative_sum(my_list))
Output
The list is : [10, 20, 25, 30, 40, 50] The cumulative sum is : [10, 30, 55, 85, 125, 175]
Explanation
A method is defined, and a list is passed as a parameter to it.
An empty list is defined.
The length of the list is determined.
The list comprehension is used to iterate over the list.
It is converted to a list, and assigned to a variable.
The list from the second element to the last element is returned as output.
A list is defined outside the function and displayed on the console.
The method is called, and the list is passed as a parameter to it.
It is displayed as output on the console.
- Related Articles
- Python program to find Cumulative sum of a list
- Program to find sum of odd elements from list in Python
- Python program to find sum of elements in list
- Program to find sum of the minimums of each sublist from a list in Python
- Program to find sum of minimum trees from the list of leaves in python
- Find sum of elements in list in Python program
- Find sum of frequency of given elements in the list in Python
- Write a program to form a cumulative sum list in Python
- Python Program to Find the Total Sum of a Nested List Using Recursion
- How to find the sum of two list elements in R?
- Program to find maximum sum of popped k elements from a list of stacks in Python
- Find the difference of the sum of list elements that are missing from Matrix and vice versa in python
- Python program to find the sum of Characters ascii values in String List
- Program to find largest sum of non-adjacent elements of a list in Python
- Program to check sublist sum is strictly greater than the total sum of given list Python

Advertisements