itertools: loop power tools

Standard Library Tour, lesson 4 of 7

🧰 Standard Library Tour, lesson 4 of 7

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?

Walkthrough

Pairs from ["Ana", "Ben", "Cy"]

AnaBenCyAnaBenCy123456
Step 1 of 2

permutations(team, 2): every ordered pair, so (Ana, Ben) and (Ben, Ana) both appear: 6 pairs. The diagonal stays empty because an item is never paired with itself.

produced
skipped

Row = first item of the pair, column = second. Numbers show the order the pairs come out.

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 items that share the same key (the item itself, unless you pass key=), 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.

Diagram

Why groupby needs sorted data

as givenbeanapplecherryavocadoblueberrybacabsortedappleavocadobeanblueberrycherryabc

Unsorted, the two "a" words aren't neighbours, so groupby starts a new group every time the key changes: 5 groups, with "a" and "b" twice. Sorted, equal keys sit together: 3 groups.

Each bracket is one group, labeled with its key (the first letter).

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.