Sub topic 11
Product, permutations and combinations
This chapter covers the itertools functions that generate arrangements of items: product, permutations and combinations. It also covers the related combinations_with_replacement. It assumes you are comfortable with loops, tuples and comprehensions, and that you know an iterator is consumed once. If you have seen for loops nested three levels deep just to try every option, this chapter replaces that code.
The working model
All four functions return a lazy iterator of tuples. They differ in two questions:
- Does the order of the chosen items matter?
('A', 'B')and('B', 'A')are different arrangements in one case and the same selection in the other. - Can an item be used more than once?
| Function | Order matters | Repeats allowed | Count for n items, r picks |
|---|---|---|---|
| `product(pool, repeat=r)` | yes | yes | n ** r |
| `permutations(pool, r)` | yes | no | n! / (n - r)! |
| `combinations(pool, r)` | no | no | n! / (r! (n - r)!) |
| `combinations_with_replacement(pool, r)` | no | yes | (n + r - 1)! / (r! (n - 1)!) |
product: every combination of choices
product takes several iterables and yields one tuple for each way of picking one item from each. It is the same as nested for loops, with the last input varying fastest.
from itertools import product
sizes = ['S', 'M']
colors = ['red', 'blue', 'green']
for size, color in product(sizes, colors):
print(size, color)This prints six lines: S red, S blue, S green, M red, M blue, M green. The loop version would need two levels of nesting, and a third input would need a third level. With product you add one argument.
The repeat keyword uses one iterable several times. product(x, repeat=2) is the same as product(x, x).
from itertools import product
print(list(product('01', repeat=2)))
print([''.join(bits) for bits in product('01', repeat=3)])The first line prints [('0', '0'), ('0', '1'), ('1', '0'), ('1', '1')]. The second prints all eight three-bit strings, from '000' to '111'.
A common use is a parameter grid. When the number of dimensions is not known in advance, unpack with *:
from itertools import product
grid = {"lr": [0.1, 0.01], "depth": [3, 5]}
for values in product(*grid.values()):
print(dict(zip(grid, values)))This prints four dictionaries, starting with {'lr': 0.1, 'depth': 3} and ending with {'lr': 0.01, 'depth': 5}. Adding a key to grid adds a dimension with no other change to the loop.
permutations: ordered picks without repeats
permutations(pool, r) yields every ordering of r items taken from the pool. If you leave out r, it uses the full length of the pool.
from itertools import permutations
print(list(permutations('ABC', 2)))
print(len(list(permutations('ABC'))))The first line prints [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]. The second prints 6, the number of ways to order three items.
Typical uses are trying every order of tasks, every seating plan, or every route through a few stops.
combinations: unordered picks without repeats
combinations(pool, r) yields each group of r items once, regardless of order.
from itertools import combinations, combinations_with_replacement
print(list(combinations('ABC', 2)))
print(list(combinations_with_replacement('ABC', 2)))The first line prints [('A', 'B'), ('A', 'C'), ('B', 'C')]. The second prints six tuples, because each item may now pair with itself: AA, AB, AC, BB, BC, CC.
Use combinations when a group is the same group in any order. An example is finding pairs of prices that add up to a target:
from itertools import combinations
prices = [4, 8, 15, 16, 23, 42]
target = 31
matches = [pair for pair in combinations(prices, 2) if sum(pair) == target]
print(matches)This prints [(8, 23), (15, 16)]. A permutations version would report each pair twice, once in each order, and do twice the work.
Output order and what counts as distinct
The output order is deterministic and follows the input order. The tuples come out in lexicographic order by item position, so if the input is sorted, the output is sorted too. You can rely on this when you need reproducible results.
These functions treat items as distinct by their position, not their value. A pool with equal values therefore produces repeated tuples:
from itertools import permutations
result = list(permutations([1, 1, 2]))
print(len(result))
print(sorted(set(result)))This prints 6 and then [(1, 1, 2), (1, 2, 1), (2, 1, 1)]. The two 1 values are treated as different items, so every distinct arrangement appears twice. If you need only distinct results, wrap in set. That stores everything in memory, so it only suits small outputs.
Counting before you generate
The number of results grows fast. Ten items taken three at a time give 720 permutations, but ten items taken eight at a time give 1,814,400. Compute the size first with math.comb, math.perm and math.prod:
import math
n, r = 5, 2
print(math.perm(n, r))
print(math.comb(n, r))
print(math.comb(n + r - 1, r))
pools = [range(10), range(10), range(10)]
print(math.prod(len(p) for p in pools))This prints 20, 10, 15 and 1000. These are the counts for permutations, combinations, combinations with replacement, and a three-digit product. Checking the count costs nothing and tells you whether a brute-force search is practical.
Laziness and what is stored
The result of each function is a lazy iterator. It does not build the list of all outputs. Memory use stays small even when the number of results is huge:
from itertools import combinations
first = next(combinations(range(1_000_000), 3))
print(first)This prints (0, 1, 2) immediately. A list of all the triples would hold about 1.7 × 10^17 tuples and could never be built.
There is one exception to laziness. Each function first reads its input fully into a tuple, called the pool, and then works from that. Three consequences follow:
- An infinite input such as
count()never finishes, because the function waits for the input to end. Bound it withislicefirst. - An iterator input is consumed during that first read. For
product, this applies to every argument, so you can safely pass a one-shot iterator andrepeatstill works. - Memory use is proportional to the size of the inputs, not the size of the output.
Edge cases
The behavior at the boundaries is consistent with the math. It is worth knowing so that an empty result does not surprise you.
from itertools import combinations, permutations, product
print(list(combinations('ABC', 4)))
print(list(combinations('ABC', 0)))
print(list(permutations('', 0)))
print(list(product()))
print(list(product('AB', [])))This prints:
[], because you cannot pick four distinct items from three.[()], because there is exactly one way to pick nothing.[()], for the same reason.[()], because a product of no inputs has one empty tuple.[], because an empty input leaves no way to choose an item from it.
The last case matters in practice. If one dimension of a parameter grid is an empty list, the whole product is empty and your loop body never runs, with no error.
Passing a negative r raises ValueError. For product, repeat must also be non-negative.
Stopping early
Because the output is lazy, you can stop at the first match and skip the rest. Use next with a generator expression and a default:
from itertools import product
digits = range(10)
found = next(
(code for code in product(digits, repeat=3) if sum(code) == 27),
None,
)
print(found)This prints (9, 9, 9). The search stops there, having tried only the codes up to that point. If nothing matched, found would be None.
Common mistakes
- Calling
list()on a large result. Iterate or stop early unless you know the count from the section above. - Reusing an exhausted result. The iterator returned by
combinations(...)is spent after one full pass. Call the function again to start over. - Using
permutationswhen order does not matter. This multiplies the work byr!and reports duplicates of the same group. - Passing
repeattogether with several iterables in a way you did not intend.product(a, b, repeat=2)is the same asproduct(a, b, a, b). - Expecting distinct values from a pool with duplicates, as shown above.
Exercise
A lock has three wheels, and each wheel shows a digit from 0 to 9. (a) How many possible codes are there, and how do you generate them? (b) How many codes are there if all three digits must differ, and which function generates them?
Show answer
(a) 1000 codes, from product(range(10), repeat=3). Each wheel is independent and digits can repeat, so the count is 10 * 3. (b) 720 codes, from permutations(range(10), 3). Order matters because 123 and 321 are different codes, and no digit repeats, so the count is math.perm(10, 3), which is 10 9 * 8.
Exercise
You have five people and need to choose a team of two. How many teams are possible, and how many ways are there to pick a captain and a vice-captain from the same five people? Name the function for each.
Show answer
There are 10 teams, from combinations(people, 2), because a team of Ana and Bo is the same team as Bo and Ana. There are 20 captain and vice-captain pairs, from permutations(people, 2), because the two roles make order matter. The counts are math.comb(5, 2) and math.perm(5, 2).