all Python 3itertoolsfunction
itertools.combinations_with_replacement
itertools
Length-r combinations allowing repeated elements.
Syntax
itertools.combinations_with_replacement(iterable, r)
Unlike combinations, the same element may be picked more than once (tuples are non-decreasing by position). Unlike product(it, repeat=r) it omits reordered duplicates — only order-independent selections — so you get C(n+r-1, r) results instead of n**r.
Examples
import itertools
print(list(itertools.combinations_with_replacement([1, 2], 2))) # → [(1, 1), (1, 2), (2, 2)]
print(list(itertools.combinations_with_replacement('ab', 3))) # → [('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'b', 'b'), ('b', 'b', 'b')]
print(len(list(itertools.combinations_with_replacement(range(6), 2)))) # → 21
print(list(itertools.combinations([1, 2], 2))) # → [(1, 2)]
print(list(itertools.combinations_with_replacement([], 2))) # → []
See also
Open in the full glossarydocs.python.orgReport an inaccuracy