Python Itertools

· by

Contents

Itertools is a tiny Python module with limited functionality. But when you can use it, it is awesome. I need to look up the names quite often. Recently, I found an explanation by Ben Blank which is simply beautiful.

product

product(*iterables, repeat=1) creates the cross product of two iterables. The length of the result is the product of the lengths of all iterables.

import itertools

list(itertools.product([1, 2, 3], ["A", "B"]))

results in

[(1, "A"), (1, "B"), (2, "A"), (2, "B"), (3, "A"), (3, "B")]

Ben Blank's Explanation:

import itertools

list(itertools.product([1, 2, 3, 4], [1, 2, 3, 4]))

results in

1,1  1,2  1,3  1,4
2,1  2,2  2,3  2,4
3,1  3,2  3,3  3,4
4,1  4,2  4,3  4,4

permutations

permutations(iterable, r=None) generates all unique orderings of unique elements. If r is not specified, all elements are taken. In an urn model, this means taking r balls without replacement.

Ben Blank's Explanation:

import itertools

list(itertools.permutations([1, 2, 3, 4], r=2))

results in

 .   1,2  1,3  1,4
2,1   .   2,3  2,4
3,1  3,2   .   3,4
4,1  4,2  4,3   .

combinations

combinations(iterable, r) generates each unique pair of elements in lexicographical order.

Ben Blank's Explanation:

import itertools

list(itertools.combinations([1, 2, 3, 4], r=2))

results in

 .   1,2  1,3  1,4
 .    .   2,3  2,4
 .    .    .   3,4
 .    .    .    .

combinations_with_replacement

combinations_with_replacement(iterable, r) is identical to combinations, except that elements can be repeated.

from itertools import combinations_with_replacement

list(combinations_with_replacement([1, 2, 3, 4], r=2))

results in

 1,1  1,2  1,3  1,4
  .   2,2  2,3  2,4
  .    .   3,3  3,4
  .    .    .   4,4