Member-only story
In Python, the itertools
module provides a powerful set of tools for working with iterators. One particularly useful function is accumulate()
, which allows you to transform and combine elements from an iterable into a new sequence. Let's dive into how accumulate()
works and explore some practical examples.
At its core, accumulate()
takes an iterable and applies a binary function to consecutive elements, accumulating the results into a new sequence. Here's a simple example:
from itertools import accumulate
numbers = [1, 2, 3, 4, 5]
accumulated_sum = list(accumulate(numbers))
print(accumulated_sum) # Output: [1, 3, 6, 10, 15]
In this example, accumulate()
applies the default binary function (operator.add
) to the elements of the numbers
list. The resulting sequence accumulated_sum
contains the running sum of the elements, where each element is the sum of the previous element and the current element.
One of the powerful aspects of accumulate()
is its ability to work with custom binary functions. For example, you can use it to compute the running product of a sequence:
from itertools import accumulate
import operator
numbers = [1, 2, 3, 4, 5]
accumulated_product = list(accumulate(numbers…