Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / Python

itertools.combinations_with_replacement

Enumerates selections whose positions may be reused while their order stays nondecreasing.

Version: Python 3.14; repository image, production runtime not attested

Syntax

itertools.combinations_with_replacement(iterable, r)

Enumerates selections whose positions may be reused while their order stays nondecreasing.

Selecting zero items yields one empty tuple, even when the input pool is empty.

Indices never decrease but a position can be chosen repeatedly, yielding AA, AB and BB. BA would reverse the index order. For r=0, choosing nothing is one valid selection, the empty tuple, even when the pool is empty.

import itertools as I
assert list(I.combinations_with_replacement("AB", 2)) == [("A","A"), ("A","B"), ("B","B")]
assert list(I.combinations_with_replacement("", 0)) == [()]

Examples

import itertools as I
print(list(I.combinations_with_replacement("AB", 2)))
print(list(I.combinations_with_replacement([], 0)))

Result

[('A', 'A'), ('A', 'B'), ('B', 'B')]
[()]

Indices never decrease but a position can be chosen repeatedly, yielding AA, AB and BB. BA would reverse the index order. For r=0, choosing nothing is one valid selection, the empty tuple, even when the pool is empty.

Sources