ID EN
Itertools

combinations_with_replacement

Python 3.11

Return r length subsequences of elements from the input iterable allowing individual elements to be repeated more than once.

Syntax

PYTHON
itertools.combinations_with_replacement(iterable, r)

Examples

Example 1
PYTHON
def combinations_with_replacement(iterable, r):
     combinations_with_replacement('ABC', 2) --> AA AB AC BB BC CC
    pool = tuple(iterable)
    n = len(pool)
    if not n and r:
        return
    indices = [0] * r
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != n - 1:
                break
        else:
            return
        indices[i:] = [indices[i] + 1] * (r - i)
        yield tuple(pool[i] for i in indices)
Example 2
PYTHON
def combinations_with_replacement(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    for indices in product(range(n), repeat=r):
        if sorted(indices) == list(indices):
            yield tuple(pool[i] for i in indices)

See Also

combinations_with_replacement() product()