How to generate combinations in Python with itertools
Generate all unique combinations of r items from a given list using itertools.combinations.
Python code
12 linesimport itertools
def combinations_generator(items, r):
return list(itertools.combinations(items, r))
if __name__ == "__main__":
items = ['A', 'B', 'C', 'D']
r = 2
result = combinations_generator(items, r)
for combo in result:
print(combo)
print(f"Total: {len(result)} combinations of {r} from {len(items)} items")
Output
('A', 'B')
('A', 'C')
('A', 'D')
('B', 'C')
('B', 'D')
('C', 'D')
Total: 6 combinations of 2 from 4 items
How it works
The itertools.combinations function returns an iterator that yields tuples of length r from the input iterable. It treats the input as ordered but ignores the order of elements within each combination, so ('A','B') and ('B','A') count as the same combination and are not both produced. Converting the iterator to a list with list() materializes all combinations at once, which is fine for small inputs but memory-heavy for large sets. The function uses the lexicographic order of the input items to determine combination ordering, so passing a sorted list gives predictable output.
Common mistakes
- Confusing combinations with permutations — combinations ignore order, permutations do not.
- Passing an integer instead of an iterable to `itertools.combinations`, which raises a TypeError.
- Forgetting that the result is a tuple iterator, so you must iterate or convert it to a list to see the values.
- Using `r` larger than the length of the input, which returns an empty list.
Variations
- Use `itertools.combinations_with_replacement(items, r)` to allow the same item to appear more than once.
- Generate combinations as a generator expression instead of a list to save memory: `(combo for combo in itertools.combinations(items, r))`.
Real-world use cases
- Building feature pairs for a recommender system where each pair of items is tested together.
- Generating all possible team pairings from a roster for scheduling practice matches.
- Testing combinations of configuration flags in an experiment framework to find valid parameter sets.
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.