How to Generate Combinations with Replacement in Python

Generate all r-length combinations with repetition from a list using the standard library itertools.combinations_with_replacement function.

Easy Python 3.9+ Aug 9, 2026 Comprehensions & generators 11 views 0 copies

Python code

12 lines
Python 3.9+
from itertools import combinations_with_replacement

items = ['A', 'B', 'C']
r = 2

combos = list(combinations_with_replacement(items, r))

for combo in combos:
    print(combo)

if __name__ == "__main__":
    print(f"Total combinations with replacement: {len(combos)}")

Output

stdout
('A', 'A')
('A', 'B')
('A', 'C')
('B', 'B')
('B', 'C')
('C', 'C')
Total combinations with replacement: 6

How it works

itertools.combinations_with_replacement yields tuples of length r where each element can repeat, ordered lexicographically. Unlike combinations, it allows the same item to appear multiple times in a single output tuple. Converting the iterator to a list with list() materializes all combos at once, which is fine for small inputs but may exhaust memory for large datasets. The if __name__ == '__main__' guard ensures the total count only prints when run directly, not when imported elsewhere.

Common mistakes

  • Confusing this with `combinations` which disallows repetition — triple-check which one your problem needs.
  • Forgetting that the result is an iterator, so you must wrap it in `list()` to reuse it multiple times.
  • Assuming order matters — this returns combinations, not permutations, so ('A', 'B') and ('B', 'A') are the same.

Variations

  1. Use `for combo in combinations_with_replacement(items, r)` directly in a loop to avoid materializing a large list in memory.
  2. Generate combinations with replacement from a range like `combinations_with_replacement(range(1, 5), 3)` for numeric work.

Real-world use cases

  • Generating all possible pizza topping combinations from a menu where customers can repeat toppings.
  • Enumerating dice roll outcomes where each face value can appear multiple times in a sequence.
  • Building test data for combinatorics problems, such as all ways to distribute identical items into bins.

Sponsored

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Comprehensions & generators

Related tutorials and quizzes for this topic.