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

PythonServer Side ProgrammingProgramming

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

 Live Demo

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.

raja
Updated on 19-Apr-2021 11:11:58

Advertisements