Module 13 · Lesson 04
itertools: Building Blocks for Iterators
Use the itertools module's fast, lazy tools: endless count and cycle, islice, chain, accumulate, pairwise and batched, grouping with groupby, and combinations, permutations and product.
- About 9 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Endless iterators, safely
- Join and pair streams
- Running totals with accumulate
- Watch steps become totals
Ready-made loop tools
itertools gives fast, lazy building blocks, so many loops become one line.
Endless
count()andcycle()go on for ever.islice()takes just the part you need.Join and pair
chain()joins streams.pairwise()gives each item with the next one.Running results
accumulate()gives running totals, or a running maximum withmax.Pick and group
combinations(),product()andgroupby()for choosing and grouping.
itertools everywhere
These tools turn up wherever data is paired, grouped or repeated.
- Turn order
cycle(players)hands out whose turn it is, round and round. - Bank balances
accumulate(payments)shows the balance after each payment. - Outfit picker
product(shirts, trousers)lists every pair you could wear. - Trip legs
pairwise(stops)gives each leg of a journey: this stop to the next.
Taking a few from for ever
This line takes three numbers from an endless count. Tap each part to see its job.
Part 1 of 7
result:A real list: [10, 15, 20].
Loops in one line
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6Endless, safely
Endless tools are safe as long as you only take what you need.
Your turn: Make count go up in tens. Then share the turns between four players.
from itertools import count, cycle, islice
print(list(islice(count(1), 5)))
turns = cycle(["Ana", "Ben", "Cai"])
for _ in range(5):
print("turn:", next(turns))Press Run to see what it prints.Watch steps become totals
Press Step to run one line at a time. Watch the names box change.
Ready. Press Step to run the first line.
- from itertools import accumulate, pairwise
- walks = [2000, 3500, 1500]
- totals = list(accumulate(walks))
- gaps = [b - a for a, b in pairwise(totals)]
- print(totals)
- print(gaps)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.repeat with a limit:
from itertools import repeat
print(list(repeat("hi", 3)))0 of 6 answered
Common itertools misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
from itertools import (count, cycle, repeat, islice, chain, pairwise,
zip_longest, batched, accumulate, groupby, combinations,
permutations, product, takewhile, dropwhile)
islice(count(1), 5) # 1 2 3 4 5
cycle("AB") # A B A B ... for ever
chain(a, b) # a's items, then b's
chain.from_iterable(lists) # flatten one level
pairwise(xs) # (x0, x1), (x1, x2), ...
batched(xs, 3) # tuples of 3 (3.12+)
accumulate(xs) # running totals
groupby(sorted(xs, key=k), key=k) # (key, group iterator)
combinations(xs, 2) # unordered pairs
permutations(xs, 2) # ordered pairs
product(a, b) # nested-loop pairs
takewhile(test, xs) # until the first failurePress Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
A weekly washing-up rota
Four flatmates take turns washing up, one per day, starting on Monday. Print the first ten days of the rota with day numbers, and show who has washed up most often in those ten days.
from itertools import count, cycle, islice
from collections import Counter
flatmates = ["Ana", "Ben", "Cai", "Dee"]
days = cycle(["Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"])
turns = cycle(flatmates)
rota = list(islice(zip(count(1), days, turns), 10))
for number, day, person in rota:
print(f"day {number:>2} {day}: {person}")
counts = Counter(person for _, _, person in rota)
print("Most turns:", counts.most_common(2))Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
groupby on unsorted data
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
from itertools import groupby
items = ['apple', 'banana', 'avocado']
for letter, group in groupby(items, key=lambda w: w[0]):
print(letter, list(group))Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Quality assurance
Building a browser test matrix
Before each release, a web team runs its checkout tests on every combination of browser, screen size and language. Some combinations are known to be unsupported. Writing the list by hand is error-prone, so they generate it, skip the exclusions, and split the rest into batches for their three test machines.
Why Python fits
productreplaces three nested loops and produces all 12 combinations in a predictable order; one is filtered out.batchedcuts the 11 remaining runs into groups of four for the machines, andcount(1)numbers them. Adding a fourth browser is a one-word change.Pythonfrom itertools import product, batched, count browsers = ["chrome", "firefox", "safari"] screens = ["phone", "desktop"] languages = ["en", "de"] unsupported = {("safari", "phone", "de")} runs = [combo for combo in product(browsers, screens, languages) if combo not in unsupported] print("Total runs:", len(runs)) for machine, batch in zip(count(1), batched(runs, 4)): print(f"machine {machine}:", ", ".join("/".join(combo) for combo in batch))OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Why use islice instead of slicing a list?
What is the difference between combinations and permutations?
Is batched available everywhere?
Are itertools functions faster than writing loops?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 15 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.