Python itertools - How to use the accumulate()

It is difficult to explain the accumulate() but it is a very useful tool for math.

import itertools
import operator

a = [1, 2, 3, 4]
b = itertools.accumulate(a, operator.add)

print(b)  # <itertools.accumulate object at 0x118019280>

for i in b:
    print(i)

# 1
# 3
# 6
# 10

The accumulate() returns the iterable producing 1, 3, 6, 10.

1 = 1
3 = 1 + 2
6 = 1 + 2 + 3
10 = 1 + 2 + 3 + 4

The second argument is an operator that is needed importing.

Python Itertools

Python Tutorial