How to create classes of iterators using itertools module in Python

The itertools module provides iterators that you can use in your projects. One of the commonly used method is accumulate.

>>> import itertools
>>> accumulator = itertools.accumulate(range(10))
>>> next(accumulator)
0
>>> next(accumulator)
1
>>> next(accumulator)
3
>>> next(accumulator)
6
>>> next(accumulator)
10
>>> next(accumulator)
15

As you can see, it makes “additions” starting from 0, then add 1, then add 2, etc.
This is a fairly simple example. As a more interesting (and a little bit more complicated), let’s take a look at combinations method.

>>> list(itertools.combinations(range(3), 2))
[(0, 1), (0, 2), (1, 2)]

Of course, you can go as difficult as you want/need.

>>> list(itertools.combinations(range(5), 3))
[(0, 1, 2), (0, 1, 3), (0, 1, 4), (0, 2, 3), (0, 2, 4), (0, 3, 4), (1, 2, 3), (1, 2, 4), (1, 3, 4), (2, 3, 4)]

Those are just a couple of examples but there is full documentation at https://docs.python.org/2/library/itertools.html.

Leave a Reply