🧰 Standard Library Tour, lesson 4 of 6
itertools: loop power tools
Combinations, products, running totals and endless cycles.
9 min
1 exercise
1 quiz
0/2 solved
Getting Python ready… examples can run in a moment.
itertools is a toolbox of looping building blocks:
combinations, permutations, running totals, grouping
and more. Its functions return lazy iterators (like
generators), so wrap them in list() to see
everything at once.
Combinations and permutations
Combinations ignore order (Ana+Ben is the same as Ben+Ana); permutations count both orders. How many 3-topping pizzas are there?
What does this print?
product, chain and accumulate
product replaces nested loops. Try
list(product("HT", repeat=3)) for every result of
three coin flips.
Endless iterators. count(start) counts forever
and cycle(seq) repeats a sequence forever. Pair them
with zip (which stops at the shortest input) or take
a slice with islice(it, n).
groupby groups neighbouring equal items, so sort
the data first.
Taking turns with cycle
Add a third person to the cycle. Never call
list(count()) on its own: it never ends!
groupby (sort first!)
Delete words.sort() and run it again: groupby only
groups items that sit next to each other.
Meal deals
Write meal_deals(menu, budget): using
combinations, return a list of every pair of dish
names whose prices add up to at most budget.
Each pair should appear once.