Itertools - accumulate()
because sometimes sum() is not enough
This is a post about itertools functions. You can see all of them Here
accumulate is a function in itertools module that allow you to have the cumulative sum of the values in an array. You may think this will have the same result as sum(), but you would be wrong.
Unlike sum, accumulate does not require the entire iterator to be loaded in memory to perform the operation, accumulate will loop the iterator, reading only the next value, being memory efficient.
Another benefit of using accumulate is the flexibility to use different functions to perform the operations. While a regular syntax of accumulate may look like:
from itertools import accumulate
x = range(100)
result = list( accumulate(x) )
print(result[-1]) # 4950We can also change use it with a custom function.
In this example, we are adding the double of the current value:
from itertools import accumulate
x = range(100)
result = list ( accumulate(x,lambda acc, value: (value *2) + acc) )
print(result[-1]) # 9900Accumulate is also good in financial applications, where you want to see the moving average, or even in other applications where you need to perform a different step, based on the cumulative value.

