Advanced Python

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

Take the level exam
  1. 1Make your own iterator

    __iter__ and __next__.

    The idea

    Ticket PY-301 from the launch team: a countdown object that a for loop can walk through, from start down to 1.

    A for loop asks the object for an iterator with __iter__, then calls __next__ again and again. __next__ gives the next value, or raises StopIteration when there is nothing left. A class that has both, with __iter__ returning self, works in every for loop and in list(...).

    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
  2. 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 gives None if 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
  3. 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 yield to hand out values one at a time. yield from other hands out everything another generator makes. So a flatten that meets a list calls itself with yield from flatten(item), and meets a product with yield 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
  4. 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), where group is an iterator, so sum(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
  5. 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 size orders starting at position start, 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
  6. 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, and yield the time and message only when the level is ERROR. 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
  7. 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 n labels per job. Split a stream of labels into jobs of n, 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 of n items 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 batch

    What 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