Using itertools.combinations_with_replacement to generate combinations with repetition

itertools.combinations_with_replacement is a useful function from the itertools module that allows you to create combinations of elements with repetition. This is convenient when you need to generate all possible combinations of a given length with repeating elements.

🗣 In this example, combinations_with_replacement is used to generate all pairs of numbers with repetition.

import itertools

items = [1, 2, 3]
combinations = list(itertools.combinations_with_replacement(items, 2))

print(combinations)

✔️ This function helps solve tasks related to generating options where repetition is allowed.

Comments (0)

Leave a comment