Python Glossary Русский

all Python 3itertoolsfunction

itertools.combinations

itertools

All length-r combinations of the iterable (no repeats, order-independent).

Syntax

itertools.combinations(iterable, r)

Elements are treated as unique by position, not by value, so duplicate inputs produce duplicate output tuples. The result count is C(n, r) and grows explosively — don't blindly list() combinations of a large input; tuples come in the input's lexicographic order, and r greater than n yields nothing.

Examples

import itertools
print(list(itertools.combinations([1, 2, 3], 2)))   # → [(1, 2), (1, 3), (2, 3)]
print([''.join(p) for p in itertools.combinations('abc', 2)])   # → ['ab', 'ac', 'bc']
print(len(list(itertools.combinations(range(5), 3))))   # → 10
print(list(itertools.combinations([3, 1, 2], 2)))   # → [(3, 1), (3, 2), (1, 2)]
print(list(itertools.combinations([1, 2], 3)))   # → []

See also

Open in the full glossarydocs.python.orgReport an inaccuracy