Sub topic 11
Product, permutations and combinations
This chapter assumes you know Python loops and comprehensions, tuples and strings, and the iterator basics from earlier chapters: iterators are lazy and can be consumed only once. Here you will generate Cartesian products, orderings and selections without writing nested loops.
The three questions
Each combinatoric function answers a different question about an input pool of items.
| Function | Order matters? | Repeats of the same position? | Result size for n items, length r |
|---|---|---|---|
| `product(pool, repeat=r)` | Yes | Yes (items can reappear) | n**r |
| `permutations(pool, r)` | Yes | No | n! / (n-r)! |
| `combinations(pool, r)` | No | No | n! / (r! (n-r)!) |
All three return lazy iterators of tuples. They treat items by position, not by value, so duplicate values in the input produce duplicate results.
product: replacing nested loops
product(a, b) is equivalent to a nested loop over a and b. The rightmost input advances fastest, like an odometer.
from itertools import product
sizes = ['S', 'M']
colors = ['red', 'blue']
for size, color in product(sizes, colors):
print(size, color)This prints S red, S blue, M red, M blue. To combine a pool with itself, use repeat.
from itertools import product
print(list(product('01', repeat=2)))The output is [('0', '0'), ('0', '1'), ('1', '0'), ('1', '1')], all two-bit tuples.
permutations and combinations
permutations(pool, r) yields every ordering of r items with no item reused. If you omit r, it uses the full length of the pool. combinations(pool, r) yields selections where order is ignored, and it emits each one in the order the items appear in the pool.
from itertools import combinations, permutations
print(list(combinations('ABC', 2)))
print(len(list(permutations('ABC', 2))))The first line prints [('A', 'B'), ('A', 'C'), ('B', 'C')]. The second prints 6, because the pairs ('A', 'B') and ('B', 'A') count separately.
A worked example: checking subsets
Suppose you want every pair of numbers from a list that sums to a target. Combinations avoid pairing an item with itself and avoid counting (a, b) and (b, a) twice.
from itertools import combinations
nums = [2, 7, 4, 5, 9]
target = 11
pairs = [p for p in combinations(nums, 2) if sum(p) == target]
print(pairs)This prints [(2, 9), (7, 4)]. Because combinations is lazy, the full list of pairs is never held in memory. Only the matches are stored.
Common errors
- Forgetting the output grows fast.
permutations(range(10))has 3,628,800 results. Iterating lazily is fine. Callinglist()on it is not. - Expecting unique values.
combinations('AAB', 2)yields('A', 'A')because the twoAitems sit at different positions. Deduplicate the input first, or wrap the output inset, if you need distinct values. - Reusing an exhausted iterator. Like other iterators, the result is consumed after one pass. Call the function again, or store the results if you need a second pass.
- Confusing
repeatwithr.producttakesrepeat=, whilepermutationsandcombinationstakeras a second positional argument.
Choosing the right function
- Ask whether the same item may appear more than once in a result. If yes, use
productwithrepeat. - Otherwise ask whether order distinguishes results. If yes, use
permutations. - If order does not matter, use
combinations. - If the pools differ, as in sizes and colors, use
productwith several arguments.
Exercise
A lock has 3 dials, each showing a digit from 0 to 9. Which itertools function lists every possible code, and how many codes are there? Write the expression that counts them without building a list.
Show answer
Use product(range(10), repeat=3), since digits can repeat and order matters. There are 103 = 1000 codes. Count them lazily with sum(1 for _ in product(range(10), repeat=3)), or compute `103` directly.
Exercise
You have 5 players and need to choose a team of 2. Which function applies, and how many teams are there? Check the count with the math module.
Show answer
Use combinations(players, 2), because order does not matter and nobody plays twice. The count is math.comb(5, 2), which is 10.