Permutations and Combinations in Python (Itertools)
Extracted from itertools — Functions creating iterators for efficient looping — Python 3.11.3 documentation
PERMUTATIONS
itertools.permutations(iterable, r=None)
returns successive r
length permutations of elements in the iterable.
If r
is not specified or is None
, then r
defaults to the length of the iterable and all possible full-length permutations are generated.
Ex.1.
1 | from itertools import permutations |
Output:
1 | (1, 2, 3) |
Ex.2.
1 | from itertools import permutations |
Output:
1 | ('A', 'B') |
Learn more here
COMBINATIONS
Notice: r
is NOT optional. (Not like permutations
)
WITH NO REPLACEMENTS
itertools.combinations(iterable, r)
returns r
length subsequences of elements from the input iterable.
Ex.
1 | from itertools import combinations |
Output:
1 | (1, 2) |
Learn more here
WITH REPLACEMENTS
itertools.combinations_with_replacement(iterable, r)
returns r
length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.
Ex.
1 | from itertools import combinations_with_replacement |
Output:
1 | (1, 1) |
Learn more here