Level recap · Advanced Python · Level 3
Iteration
Everything this level taught, class by class: the idea, the code and what it shows. Read it before the exam, or keep it as a PDF.
What this level teaches: Your own iterators, generators and lazy pipelines that read only what they need.
7 classesLevel exam
1Make your own iterator
__iter__ and __next__.
The idea
Ticket PY-301 from the launch team: a countdown object that a
forloop can walk through, fromstartdown to 1.A
forloop asks the object for an iterator with__iter__, then calls__next__again and again.__next__gives the next value, or raisesStopIterationwhen there is nothing left. A class that has both, with__iter__returningself, works in everyforloop and inlist(...).The code
class Countdown: def __init__(self, start): self.current = start def __iter__(self): return self def __next__(self): if self.current <= 0: raise StopIteration self.current -= 1 return self.current + 1 print(list(Countdown(3)))What it shows
PASS Right on new test values
2Stop at the first match
A generator expression with next().
The idea
Ticket PY-302 from the warehouse: find the first order at or above a limit in a feed that can be very long, and stop reading the moment you find it.
A generator expression looks like a list comprehension in round brackets:
(o["id"] for o in orders if o["total"] >= limit). It makes values only when asked.next(gen, None)asks for the first one, or givesNoneif there is none. The rest of the feed is never read.The code
def first_big(orders, limit): return next((order["id"] for order in orders if order["total"] >= limit), None) print(first_big([{"id": 1, "total": 90}, {"id": 2, "total": 700}], 500))What it shows
PASS Right on new test values
3Walk nested lists: yield from
A recursive generator.
The idea
Ticket PY-303 from the catalog team: categories hold products and smaller categories, nested to any depth. List every product, left to right.
A generator function uses
yieldto hand out values one at a time.yield from otherhands out everything another generator makes. So aflattenthat meets a list calls itself withyield from flatten(item), and meets a product withyield item. Any depth works.The code
def flatten(tree): for item in tree: if isinstance(item, list): yield from flatten(item) else: yield item print(list(flatten(["A", ["B", ["C"]]])))What it shows
PASS Right on new test values
4Runs of the same value: groupby
itertools.groupby.
The idea
Ticket PY-304 from the operations lead: the line's status is logged every minute. Summarize it as runs: up for 12 minutes, down for 3, up for 40.
itertools.groupby(items)walks the items and groups neighbors that are equal. Each group comes as(value, group), wheregroupis an iterator, sosum(1 for _ in group)counts it. Only neighbors are grouped: the same value later starts a new run.The code
from itertools import groupby def runs(statuses): return [(status, sum(1 for _ in group)) for status, group in groupby(statuses)] print(runs(["up", "up", "down", "up"]))What it shows
PASS Right on new test values
5One page of a long feed: islice
itertools.chain and islice.
The idea
Ticket PY-305 from the web team: the order feed comes from several warehouses, one list each. The page shows
sizeorders starting at positionstart, counted across all of them.chain(*lists)reads several lists one after another as one stream, without copying them.islice(stream, start, start + size)takes that slice of any stream, even one you can't index. Together they give one page.The code
from itertools import chain, islice def page(feeds, start, size): return list(islice(chain(*feeds), start, start + size)) print(page([["HS-1", "HS-2"], ["HS-3", "HS-4"]], 1, 2))What it shows
PASS Right on new test values
6A lazy pipeline over a log
Generators chained as steps.
The idea
Ticket PY-306 from the platform team: the server log is millions of lines. The alert screen shows the first few errors, so reading the whole file first is far too slow.
A generator only does work when the next value is asked for. Write
error_lines(lines)as a generator: for each line, split it, andyieldthe time and message only when the level isERROR. The caller can stop after three errors, and the rest of the log is never read.The code
def error_lines(lines): for line in lines: date, time, level, message = line.split(" ", 3) if level == "ERROR": yield time, message print(list(error_lines(["2026-06-01 10:00:01 ERROR db: timeout", "2026-06-01 10:00:02 INFO api: ok"])))What it shows
PASS Right on new test values
7On your own: batches for the label printer
A generator that groups items, with no gold line.
The idea
Ticket PY-307 from the warehouse: the label printer takes at most
nlabels per job. Split a stream of labels into jobs ofn, the last one smaller if needed, without loading the whole stream. Plan it: what do you keep between yields?In the code box, write a generator function
batched(items, n)that yields lists ofnitems in order, and a last, shorter list if items are left over. No empty list at the end. Then press Run my code.The code
def batched(items, n): batch = [] for item in items: batch.append(item) if len(batch) == n: yield batch batch = [] if batch: yield batchWhat it shows
PASS Right on new test values
Ready for the exam? The level exam is one real task that uses what this recap covers.
Take the level exam