Python Function Reference

itertools.combinations

Iterate over combinations: groups of r items regardless of order.

Python 3.13
itertools.combinations(iterable, r)

Parameters

iterableIterable
The items to combine.
rint
How many items are in one combination.

Return value

An iterator of tuples in the order of the original items.

Examples

Combinations of two items

Python 3.13
from itertools import combinations

print(list(combinations('abc', 2)))
[('a', 'b'), ('a', 'c'), ('b', 'c')]

Pairs of numbers that add up to 10

Python 3.13
from itertools import combinations

numbers = [2, 8, 5, 5, 3]
print([pair for pair in combinations(numbers, 2) if sum(pair) == 10])
[(2, 8), (5, 5)]

Details

Order does not matter: of (a, b) and (b, a), only the first is produced. Combinations with repeated items are given by itertools.combinations_with_replacement. If r is greater than the number of items, the result is empty.

See also