itertools
Some problems ask you to list every possible pair, ordering, or combination. You can write these with a plain loop or with recursive backtracking. Python’s itertools module already has most of them built in. It’s worth knowing what’s in there. You can use it to check your own answer, or use it directly when a problem doesn’t ask you to write that part yourself.
combinations vs permutations
order matters?combinations(iterable, r) gives every group of r items where order doesn't matter. permutations(iterable, r) gives every ordering of r items. That means it gives you more results:
from itertools import combinations, permutations
letters = ["a", "b", "c"]
print(list(combinations(letters, 2)))
print(list(permutations(letters, 2)))Neither of these uses the same position twice. combinations_with_replacement(iterable, r) can use a position more than once. That means an item can pair with itself:
from itertools import combinations_with_replacement
letters = ["a", "b", "c"]
print(list(combinations_with_replacement(letters, 2)))Note
Notice ("a", "a") only shows up in the combinations_with_replacement result. Regular combinations never pairs an element with itself. It picks each item by position and never goes back to a position it already used.
product: the cartesian product
repeat=product() gives every combination of one item from each list you pass in. You’d get the same thing by nesting one for loop for each list:
from itertools import product
print(list(product([1, 2], ["x", "y"])))Sometimes you want to combine a list with itself several times, like every length-3 sequence of 0s and 1s. Pass repeat= instead of writing the same list out over and over:
from itertools import product
print(list(product([0, 1], repeat=3)))The groupby trap: consecutive keys only
watch outgroupby(iterable) puts elements with the same key into one group, but only when they’re next to each other. It doesn’t check earlier or later elements. If the same key shows up again later with something else in between, it starts a new group. It doesn’t join the earlier one:
from itertools import groupby
data = ["a", "a", "b", "a", "a"]
groups = [(key, list(group)) for key, group in groupby(data)]
print(groups)Sort by the same key first so all the equal elements are next to each other. Then they all go into one group:
from itertools import groupby
data = ["a", "a", "b", "a", "a"]
groups_sorted = [(key, list(group)) for key, group in groupby(sorted(data))]
print(groups_sorted)Note
The unsorted version above produces three groups: two runs of "a" with a "b" group in between. This is the most common groupby mistake. Remember to check whether the input is sorted by the key you’re grouping on if your groups look wrong.
accumulate: running totals, and chain: flattening
accumulate() returns a running total. You’d get the same numbers by keeping a running sum in a loop:
from itertools import accumulate
nums = [1, 2, 3, 4]
print(list(accumulate(nums)))chain() goes through several lists one after another, as if they were one list. It doesn’t build a combined list first:
from itertools import chain
print(list(chain([1, 2], [3, 4], [5])))Everything here is a lazy, one-shot iterator
gotchaNone of these functions build a list up front. Each one returns an iterator that makes values one at a time as you ask for them. Once you’ve pulled every value out, the iterator is empty. Looping over it again gives you nothing:
from itertools import combinations
pairs = combinations([1, 2, 3], 2)
first_pass = list(pairs)
second_pass = list(pairs)
print(first_pass)
print(second_pass)Note
second_pass comes back empty. first_pass already used up every value pairs had. An empty iterator doesn’t reset itself. Wrap the call in list() right away if you need to look at the results more than once. Then reuse that list.
Where itertools shows up in interviews
Interviewers almost always want you to build combinations or permutations yourself with recursive backtracking. That’s the pattern they’re testing. You can use itertools afterward to check your output against the built-in version:
- Subsets asks for every subset of a list. You’d get the same thing by calling
combinations()for every possible length. The expected solution builds it with backtracking, though. - Permutations asks for every ordering of a list. That’s the same output
itertools.permutations()returns. Here too, the interviewer expects backtracking.