w3resource

Python: Compute cumulative sum of numbers of a given list

Python Basic - 1: Exercise-92 with Solution

Write a Python program to compute the cumulative sum of numbers in a given list.
Note: Cumulative sum = sum of itself + all previous numbers in the said list.

Sample Solution:

Python Code:

def nums_cumulative_sum(nums_list):
  return [sum(nums_list[:i+1]) for i in range(len(nums_list))]

print(nums_cumulative_sum([10, 20, 30, 40, 50, 60, 7]))
print(nums_cumulative_sum([1, 2, 3, 4, 5]))
print(nums_cumulative_sum([0, 1, 2, 3, 4, 5]))

Sample Output:

[10, 30, 60, 100, 150, 210, 217]
[1, 3, 6, 10, 15]
[0, 1, 3, 6, 10, 15]

Pictorial Presentation:

Python: Compute cumulative sum of numbers of a given list.
Python: Compute cumulative sum of numbers of a given list.

Flowchart:

Flowchart: Python - Compute cumulative sum of numbers of a given list.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to count the number of arguments in a given function.
Next: Write a Python program to find the middle character(s) of a given string. If the length of the string is even return the two middle characters. If the length of the string is odd, return the middle character.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.