Partial Sum List

PythonPythonBeginner
Practice Now

This tutorial is from open-source community. Access the source code

Introduction

In mathematics, a partial sum is the sum of the first n terms of a series. In Python, we can create a list of partial sums using the itertools.accumulate() function. In this challenge, you will create a function that takes a list of numbers and returns a list of partial sums.

Partial Sum List

Write a function partial_sum(lst) that takes a list of numbers as an argument and returns a list of partial sums. Your function should perform the following steps:

  1. Use itertools.accumulate() to create the accumulated sum for each element in the list.
  2. Use list() to convert the result into a list.
  3. Return the list of partial sums.
from itertools import accumulate

def cumsum(lst):
  return list(accumulate(lst))
cumsum(range(0, 15, 3)) ## [0, 3, 9, 18, 30]

Summary

In this challenge, you learned how to create a list of partial sums using the itertools.accumulate() function. You also wrote a function that takes a list of numbers and returns a list of partial sums. This is a useful technique in mathematics and programming, and can be used in a variety of applications.

Other Python Tutorials you may like