Python 3D Academyবাংলা

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:

  1. count(start, step) counts forever; islice(it, n) takes just the first n
  2. chain(a, b) goes through a, then b, as if they were one list
  3. product(a, b) gives every pair: each item of a with each item of b
  4. combinations(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 each
  • combinations(items, k): groups of k where order doesn't matter
  • permutations(items, k): arrangements of k where order matters
  • count(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)))
count never stops, so never write list(count()): it would run forever. islice takes a few and stops.
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)
product is a nested for loop in one line: for each main, every drink. 2 mains times 2 drinks is 4 combos.

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, so list(count()) runs forever; take what you need with a loop and break, or zip it with something finite.
  • Reusing the result. Like every iterator, it's used up after one pass.

Quiz

  1. What does this print?

    from itertools import count, islice
    
    print(list(islice(count(10, 5), 3)))
  2. What does this print?

    from itertools import chain
    
    print(list(chain([1, 2], "ab")))
  3. What does this print?

    from itertools import product
    
    print(len(list(product("abc", [1, 2]))))
  4. What does this print?

    from itertools import combinations
    
    print(list(combinations("abc", 2)))
  5. 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
  6. 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

  1. Write menu_combos(mains: list[str], drinks: list[str]) -> list[str] with product: every combo as "main + drink", mains in order, and for each main the drinks in order.

  2. Write matches(teams: list[str]) -> list[tuple[str, str]] with combinations: every match in a round where each team plays every other team once.

  3. Some buildings skip unlucky floor and token numbers. Write lucky_tokens(start: int, n: int) -> list[int]: the first n numbers counting up from start that don't contain the digit 4. Use count and islice.