itertools: counting, chaining and combining
🌍 In real life. A restaurant's combo board: pick one main and one drink. How many combos are there, and what are they? A cricket coach picks 2 openers from 4 batters: which pairs are possible? A token machine at the bank prints 101, 102, 103... forever.
The itertools module answers all of these, and like the generators of Chapter 26 it hands out items one at a time instead of building everything at once. Step by step:
count(start, step)counts forever;islice(it, n)takes just the first nchain(a, b)goes througha, thenb, as if they were one listproduct(a, b)gives every pair: each item ofawith each item ofbcombinations(items, k)gives every group of k, where order doesn't matter
The idea in one sentence: itertools makes the sequences you'd otherwise build with nested loops: every combo (product), every unordered group (combinations), every ordering (permutations), and endless counters (count).
Its words:
product(a, b): every pair, one from eachcombinations(items, k): groups of k where order doesn't matterpermutations(items, k): arrangements of k where order matterscount(start),chain(a, b): an endless counter; one sequence after another
from itertools import count, islice
tokens = count(101)
print(next(tokens), next(tokens))
print(list(islice(tokens, 3)))
evens = count(0, 2)
print(list(islice(evens, 5)))from itertools import chain, product
morning = ["Mina", "Rafi"]
evening = ["Tara"]
for name in chain(morning, evening):
print("shift:", name)
mains = ["biryani", "khichuri"]
drinks = ["lassi", "tea"]
combos = list(product(mains, drinks))
print(len(combos), "combos")
for main, drink in combos:
print(main, "+", drink)Groups where order doesn't matter. Opening with Mina and Rafi is the same pair as Rafi and Mina, so combinations lists each pair only once, in the order the players were given. When order does matter (gold and silver medals are different), use permutations instead.
from itertools import combinations, permutations
batters = ["Mina", "Rafi", "Tara", "Zara"]
openers = list(combinations(batters, 2))
print(len(openers), "pairs")
print(openers[:3])
medals = list(permutations(["Mina", "Rafi", "Tara"], 2))
print(len(medals), "gold-silver results")
print(medals[:2])Four more everyday tools.
groupby(items, key): runs of items next to each other that share a key. It only groups items that are side by side, so sort by the same key first if they aren't.batched(items, n): chunks of n (the last one may be shorter): teams of two, pages of ten.pairwise(items): each item with the next one, for changes from day to day.accumulate(items): running totals (Chapter 38 calls them prefix sums).
from itertools import accumulate, batched, groupby, pairwise
sales = [("Mon", 50), ("Mon", 20), ("Tue", 40), ("Wed", 10), ("Wed", 30)]
for day, rows in groupby(sales, key=lambda row: row[0]):
print(day, sum(amount for _, amount in rows))
print(list(batched(["Ana", "Bo", "Cy", "Di", "Ed"], 2)))
print([b - a for a, b in pairwise([10, 13, 11, 18])])
print(list(accumulate([50, 20, 40])))What it costs. These are lazy, so they cost nothing until you loop, but the number of results grows very fast: 10 players make 120 groups of 3, and 10 make 3,628,800 orderings of all 10. Count before you list() a big one.
Mistakes and edge cases.
- combinations when order matters. (gold, silver) and (silver, gold) are different medals; use
permutations. - list(count()).
count()never ends, solist(count())runs forever; take what you need with a loop andbreak, orzipit with something finite. - Reusing the result. Like every iterator, it's used up after one pass.
Quiz
What does this print?
from itertools import count, islice print(list(islice(count(10, 5), 3)))What does this print?
from itertools import chain print(list(chain([1, 2], "ab")))What does this print?
from itertools import product print(len(list(product("abc", [1, 2]))))What does this print?
from itertools import combinations print(list(combinations("abc", 2)))Why is
list(count())a bad idea?- count never ends, so the list never finishes
- count needs a start number
- count gives back a string
Gold and silver are different medals, so (Rimi, Bo) and (Bo, Rimi) should both be listed. Which line is wrong?
from itertools import combinations runners = ["Rimi", "Bo", "Cy"] medals = list(combinations(runners, 2)) print(len(medals))
Coding tasks
Write
menu_combos(mains: list[str], drinks: list[str]) -> list[str]withproduct: every combo as"main + drink", mains in order, and for each main the drinks in order.Write
matches(teams: list[str]) -> list[tuple[str, str]]withcombinations: every match in a round where each team plays every other team once.Some buildings skip unlucky floor and token numbers. Write
lucky_tokens(start: int, n: int) -> list[int]: the firstnnumbers counting up fromstartthat don't contain the digit 4. Usecountandislice.