Python arrays and combinations of itertools

  • 2020-04-02 09:49:10
  • OfStack

Python 2.6 introduced the itertools module, which makes the implementation of permutation and composition very simple:

import itertools  

Order: e.g., choose two of the four permutations:

>>> print list(itertools.permutations([1,2,3,4],2))
[(1, 2), (1, 3), (1, 4), (2, 1), (2, 3), (2, 4), (3, 1), (3, 2), (3, 4), (4, 1), (4, 2), (4, 3)]

Unordered combination: e.g., 2 out of 4:

>>> print list(itertools.combinations([1,2,3,4],2))
[(1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4)]

Related articles: