2 min read

Python Itertools Module

The itertools module implements a number of iterator building blocks inspired by constructs from APL, Haskell, and SML. It provides a set of fast, memory-efficient tools that are useful by themselves or in combination.

Importing the Module

import itertools

Infinite Iterators

count()

Make an iterator that returns evenly spaced values starting with number start.

import itertools

for i in itertools.count(10):
    if i > 15:
        break
    print(i)
# Output: 10, 11, 12, 13, 14, 15

cycle()

Make an iterator returning elements from the iterable and saving a copy of each. When the iterable is exhausted, return elements from the saved copy. Repeats indefinitely.

import itertools

count = 0
for i in itertools.cycle('AB'):
    if count > 3:
        break
    print(i)
    count += 1
# Output: A, B, A, B

repeat()

Make an iterator that returns object over and over again. Runs indefinitely unless the times argument is specified.

import itertools

for i in itertools.repeat("Hello", 3):
    print(i)
# Output: Hello, Hello, Hello

Combinatoric Iterators

product()

Cartesian product of input iterables. Equivalent to nested for-loops.

import itertools

print(list(itertools.product('AB', '12')))
# Output: [('A', '1'), ('A', '2'), ('B', '1'), ('B', '2')]

permutations()

Return successive r-length permutations of elements in the iterable.

import itertools

print(list(itertools.permutations('AB', 2)))
# Output: [('A', 'B'), ('B', 'A')]

combinations()

Return r-length subsequences of elements from the input iterable.

import itertools

print(list(itertools.combinations('ABC', 2)))
# Output: [('A', 'B'), ('A', 'C'), ('B', 'C')]

Terminating Iterators

accumulate()

Make an iterator that returns accumulated sums, or accumulated results of other binary functions.

import itertools

data = [1, 2, 3, 4, 5]
print(list(itertools.accumulate(data)))
# Output: [1, 3, 6, 10, 15]

chain()

Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted.

import itertools

print(list(itertools.chain('ABC', 'DEF')))
# Output: ['A', 'B', 'C', 'D', 'E', 'F']

programming/python/python