Python: Cumulative sum of the elements of a given list
Python List: Exercise - 267 with Solution
Write a Python program to get the cumulative sum of the elements of a given list.
Sample Solution:
Python Code:
# Import the 'accumulate' function from the 'itertools' module.
from itertools import accumulate
# Define a function named 'cumsum' that computes the cumulative sum of a list.
def cumsum(lst):
# Use the 'accumulate' function to calculate the cumulative sum and convert it to a list.
return list(accumulate(lst))
# Create a sample list 'nums' with integer elements.
nums = [1, 2, 3, 4]
# Print the original list elements.
print("Original list elements:")
print(nums)
# Calculate and print the cumulative sum of the elements in the list using the 'cumsum' function.
print("Cumulative sum of the elements of the said list:")
print(cumsum(nums))
# Create another sample list 'nums' with integer elements, including negative values.
nums = [-1, -2, -3, 4]
# Print the original list elements.
print("\nOriginal list elements:")
print(nums)
# Calculate and print the cumulative sum of the elements in the list using the 'cumsum' function.
print("Cumulative sum of the elements of the said list:")
print(cumsum(nums))
Sample Output:
Original list elements: [1, 2, 3, 4] Cumulative sum of the elements of the said list: [1, 3, 6, 10] Original list elements: [-1, -2, -3, 4] Cumulative sum of the elements of the said list: [-1, -3, -6, -2]
Flowchart:
Python Code Editor:
Previous: Write a Python program to cast the provided value as a list if it's not one.
Next: Write a Python program to get a list with n elements removed from the left, right.
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.
https://198.211.115.131/python-exercises/list/python-data-type-list-exercise-267.php
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics