How to Use itertools.combinations in Python: Simple Guide
Use
itertools.combinations(iterable, r) to get all possible combinations of length r from the iterable. It returns an iterator of tuples, each tuple representing one combination.Syntax
The itertools.combinations function takes two main arguments:
iterable: The collection of items you want to combine.r: The number of items in each combination.
It returns an iterator that produces tuples of length r, each tuple being a unique combination without repetition.
python
import itertools
combinations = itertools.combinations(iterable, r)Example
This example shows how to get all 2-item combinations from a list of fruits.
python
import itertools fruits = ['apple', 'banana', 'cherry'] combos = itertools.combinations(fruits, 2) for combo in combos: print(combo)
Output
('apple', 'banana')
('apple', 'cherry')
('banana', 'cherry')
Common Pitfalls
Common mistakes include:
- Using
combinationswhen you want permutations (order matters). - Setting
rlarger than the length of the iterable, which returns no results. - Forgetting that
combinationsreturns an iterator, so you can only loop through it once unless converted to a list.
python
import itertools items = [1, 2, 3] # Wrong: r larger than length print(list(itertools.combinations(items, 4))) # Outputs [] # Right: r within length print(list(itertools.combinations(items, 3))) # Outputs [(1, 2, 3)]
Output
[]
[(1, 2, 3)]
Quick Reference
| Function | Description |
|---|---|
| itertools.combinations(iterable, r) | All unique combinations of length r from iterable |
| itertools.permutations(iterable, r) | All ordered arrangements of length r from iterable |
| itertools.combinations_with_replacement(iterable, r) | Combinations allowing repeated elements |
Key Takeaways
Use itertools.combinations to get unique groups of items without caring about order.
The second argument r must be less than or equal to the length of the iterable.
combinations returns an iterator, so convert to list if you need to reuse results.
For order-sensitive arrangements, use permutations instead of combinations.
combinations_with_replacement allows repeated elements in combinations.