itertools: loop power tools

Standard Library Tour, lesson 4 of 6

🧰 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.

Example

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?

Quiz

What does this print?

Example

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.

Example

Taking turns with cycle

Add a third person to the cycle. Never call list(count()) on its own: it never ends!

Example

groupby (sort first!)

Delete words.sort() and run it again: groupby only groups items that sit next to each other.

Exercise

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.