• Martin Thoma
  • Home
  • Categories
  • Tags
  • Archives
  • Support me

Python Itertools

Contents

  • Python Itertools
    • product
    • permutations
    • combinations
    • combinations_with_replacement

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 length 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 Blanks 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 all are taken. In an urn model, this means taking r balls without replacement.

Ben Blanks 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 Blanks 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 one has duplicate elements.

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

Published

Dez 9, 2019
by Martin Thoma

Category

Code

Tags

  • combinations 1
  • itertools 2
  • permutations 1
  • Python 141

Contact

  • Martin Thoma - A blog about Code, the Web and Cyberculture
  • E-mail subscription
  • RSS-Feed
  • Privacy/Datenschutzerklärung
  • Impressum
  • Powered by Pelican. Theme: Elegant by Talha Mansoor