Course outline · 0% complete

0/27 lessons0%

Course overview →

itertools: ready-made iteration tools

lesson 6-2 · ~11 min · 16/27

Ready-made iterator recipes

Every engineer eventually needs "all pairs of players", "these two lists glued together", or "the first 100 of an endless sequence". Writing those as nested index loops is slow to read and easy to get wrong, so the standard library ships them pre-built and pre-tested. itertools is that toolbox: lazy iterator builders, the same laziness you built by hand with generators in lesson 4-2. The ones you will reach for most:

ToolWhat it yields
chain(a, b)all of a, then all of b
product(a, b)every pairing, like nested loops
combinations(a, 2)each unordered pair, no repeats
permutations(a, 2)each ordered pair
islice(it, 5)first 5 items of any iterator
count(10)10, 11, 12, ... forever

Because results are lazy iterators, wrap them in list(...) to look at them, or loop directly. islice(it, 5) stops asking after five items, which makes it the safe way to sample an infinite iterator like count; a plain list(count(10)) would try to build an endless list and never finish.

Code exercise · python

Run this program. combinations gives you every pair of players exactly once, ideal for a round-robin schedule.

Code exercise · python

Your turn. Use product to print every (size, color) menu combination, one per line, formatted as "size color". Order: sizes outer, colors inner.

Quiz

How many items does list(combinations([1, 2, 3, 4], 2)) contain?

Quiz

What does list(islice(count(1), 3)) evaluate to?