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.
Python code
12 linesfrom 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
('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
- Use `for combo in combinations_with_replacement(items, r)` directly in a loop to avoid materializing a large list in memory.
- 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
More from Comprehensions & generators
- Batch Rows in Chunks with a Generator in Python easy
- Build a Generator Pipeline in Python: Filter Then Map medium
- Build a lazy generator to read file lines in Python easy
- Chunk an Iterable into Batches with a Generator in Python easy
- Convert Data in Python with Comprehensions and Generators easy
- Count Data in Python with Comprehensions and Generators easy
Keep learning
Related tutorials and quizzes for this topic.