Sub topic 3
Product, permutations, combinations, and iterator pipelines
Assume you know Python functions, comprehensions, lambda, and the difference between a list and a generator. The itertools functions in this chapter return iterators, so results are produced only when requested.
Product, permutations and combinations
These tools generate structured choices without writing nested loops:
productreturns the Cartesian product. It chooses one item from each input. Userepeatto reuse one input.permutationsreturns ordered arrangements. Each item can appear once.combinationsreturns unordered selections. Each item can appear once.
from itertools import combinations, permutations, product
print(list(product("AB", repeat=2)))
print(list(permutations("ABC", 2)))
print(list(combinations("ABC", 2)))The output is:
[('A', 'A'), ('A', 'B'), ('B', 'A'), ('B', 'B')]
[('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
[('A', 'B'), ('A', 'C'), ('B', 'C')]These iterators avoid storing all results at once. However, the number of possible results can still be enormous.
Copying an iterator with `tee`
An iterator normally has one position. tee creates independent views over the same source:
from itertools import tee
source = iter([10, 20, 30])
first, second = tee(source)
print(next(first))
print(next(second))
print(list(first))
print(list(second))tee saves items that one copy has consumed while another copy is behind. A large gap between copies can therefore require substantial memory.
Building lazy pipelines
Iterator tools compose naturally. Each stage receives values from the previous stage only when the final consumer asks for them.
from itertools import count, islice, product
pairs = product(count(1), "AB")
selected = (f"{number}{letter}" for number, letter in pairs)
print(list(islice(selected, 5)))Common pitfalls and when not to use `itertools`
- Do not convert an infinite iterator to
list; bound it withislice. - Do not expect an exhausted iterator to restart. Create a new iterator when needed.
product,permutations, andcombinationsmay produce combinatorial growth. Check the result count first.teeis unsuitable when consumers move far apart.- Use ordinary lists when you need repeated indexing, random access, or simple debugging.
itertoolsis most useful for one-pass processing and lazy pipelines.
Exercise
Which tool generates unordered selections of two distinct items from "ABCD"?
Show answer
combinations("ABCD", 2).