Skip to content

`itertools` products, permutations, and combinations [ref]

Problem

  • Form the Cartesian product of "ab" and "12".
  • Join every pair in that product into a string.
  • List permutations of [1, 2].
  • List two-element combinations of ["a", "b", "c"].
  • Unpack ["ab", "xy"] into arguments to product.

Python solution

from itertools import product, permutations, combinations

list(product("ab", "12"))
# [('a', '1'), ('a', '2'), ('b', '1'), ('b', '2')]

["".join(chars) for chars in product("ab", "12")]
# ['a1', 'a2', 'b1', 'b2']

list(permutations([1, 2]))  # [(1, 2), (2, 1)]

list(combinations(["a", "b", "c"], 2))
# [('a', 'b'), ('a', 'c'), ('b', 'c')]

choices = ["ab", "xy"]
list(product(*choices))
# [('a', 'x'), ('a', 'y'), ('b', 'x'), ('b', 'y')]