ID EN
Itertools

combinations

Python 3.11

Return r length subsequences of elements from the input iterable.

Syntax

PYTHON
itertools.combinations(iterable, r)

Examples

Example 1
PYTHON
def combinations(iterable, r):
     combinations('ABCD', 2) --> AB AC AD BC BD CD
     combinations(range(4), 3) --> 012 013 023 123
    pool = tuple(iterable)
    n = len(pool)
    if r > n:
        return
    indices = list(range(r))
    yield tuple(pool[i] for i in indices)
    while True:
        for i in reversed(range(r)):
            if indices[i] != i + n - r:
                break
        else:
            return
        indices[i] += 1
        for j in range(i+1, r):
            indices[j] = indices[j-1] + 1
        yield tuple(pool[i] for i in indices)
Example 2
PYTHON
def combinations(iterable, r):
    pool = tuple(iterable)
    n = len(pool)
    for indices in permutations(range(n), r):
        if sorted(indices) == list(indices):
            yield tuple(pool[i] for i in indices)

See Also

combinations() permutations()