01A.5 Comprehensions, Iterators and Generators

FoundationsLesson 5 of 119,319 words5 parts
Module 01A · 0 of 11 lessons done
  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11

This lesson is where Python starts to feel like Python. Comprehensions let you build whole collections in a single expression. The iteration protocol — the small set of rules behind every for loop — explains what is actually happening when you loop over anything. Generators let you produce values one at a time, lazily, which is how you process files, streams and pipelines that are far too large to hold in memory. Together they are the idioms you will use on almost every line of AI-engineering code you write: filtering records, batching API calls, streaming model output, chunking documents and feeding embedding pipelines.

What you'll learn

  • List, dictionary and set comprehensions: filtering, transforming, and the readability rules for when a plain loop is clearer
  • Generator expressions and how any()/all() short-circuit
  • Comprehension scope rules, and the walrus operator's surprising leak
  • The iteration protocol: iterables vs iterators, iter(), next() and StopIteration — what for really does
  • enumerate, zip (including strict=True), zip_longest, reversed, sorted, range, and why map/filter mostly lose to comprehensions
  • Unpacking in loops, and iterating dicts, sets and files
  • Generators: yield, state between yields, laziness and real memory measurements, yield from, send()/close(), infinite generators and exhaustion bugs
  • A full generator pipeline on the ticket data: read → clean → classify → batch → report, plus a memory comparison
  • A pure-Python text chunker built from generators (the real strategies are 05.6 and 05.7)
  • The itertools toolbox: chain, islice, batched (and the 3.11 fallback), groupby, takewhile, tee, the combinatorics functions, functools.reduce and operator.itemgetter
  • Sorting and searching idioms: sorted/min/max with key=, bisect, heapq.nlargest
  • A one-paragraph preview of async iteration (owned properly by Module 01B)

What you don't need

  • Classes. This lesson uses built-in types only; dataclasses arrive in 01A.6.
  • Async. You will see async for once, in a clearly marked preview; Module 01B owns async Python.
  • File formats. The pipeline reads Python objects; reading JSON/CSV from disk is 01A.9.

Setup

Everything here is the Python standard library — nothing to install and no API key needed. You need Python 3.11 or newer (3.13 or newer recommended; as of November 2026 the current stable release is Python 3.15, and every sample in this lesson runs on 3.11+ unless it is marked as needing a newer version). If you haven't set up Python yet, Module 00, lesson 00.1 walks through it; the shortest route is:

bash
uv python install 3.13     # or: install from python.org
uv run python --version    # check what you're running

Save each script below as its own .py file and run it with python3 script.py (or uv run script.py). One shared data file, tickets_data.py, is introduced where it is first needed — create it exactly as shown.


What you must be able to do after this lesson#

  • Write list, dict and set comprehensions and know when a loop is clearer
  • Explain what a for loop does with iter and next
  • Write a generator with yield
  • Explain why generators save memory
  • Chain steps into a lazy generator pipeline
  • Sort and pick items with key functions

Why this matters for an AI engineer#

You will not write a for loop over a list very often in idiomatic Python — but you will write iteration code constantly, in less obvious places:

You'll hear... You'll understand it after...
"Just use a comprehension, it's clearer." Part 1: Comprehensions
"That list comprehension will hold a million dicts in memory." 3.2 Laziness and memory
"The SDK stream is an iterator — you have to close it." 3.6 send(), close() and cleanup and 3.7
"Batch the embedding requests." 4.1 itertools.batched and 06.2
"groupby gave us the wrong groups." 4.2 groupby needs sorted input
"zip silently dropped rows." 2.4 zip(strict=True)
"next() raised StopIteration inside my function." 2.2 iter(), next() and StopIteration and the gallery
"Chunk the document before embedding it." 3.5 The text chunker and 05.6
"Stream the model's tokens to the UI." 3.7 Generators as the basis of streaming and 03.3
"The batch job reads JSONL line by line." 2.5 Unpacking in loops and 03.9

Part 1: Comprehensions — collections in one expression#

A comprehension builds a new collection by transforming and/or filtering the items of an existing one, written as a single expression instead of a loop with append calls. Python has three: list comprehensions, dictionary comprehensions and set comprehensions. They all share one shape:

text
[ expression for item in iterable  if condition ]
{ key: value for item in iterable  if condition }
{ expression for item in iterable  if condition }

Read it aloud as: "for each item in the iterable, if the condition holds, compute the expression." The if is optional; so is everything after the first for except the expression.

1.1 The three comprehensions#

Our running example is the support-ticket triage toolkit: a list of ticket dictionaries. Each lesson in this module carries its own small literal slice of that world — the datasets are regenerated per lesson so every example stays compact and deterministic (01A.4's ticket_records.py is that lesson's cast; this is yours). Here is the data file — save it as tickets_data.py:

python
# tickets_data.py — this lesson's slice of the module's ticket world:
# deterministic sample tickets for the triage examples.

TICKETS = [
    {"id": "T-101", "subject": "Cannot log in after password reset",
     "body": "Customer reset password via the email link but the new password is rejected at sign-in.",
     "status": "open", "priority": "high", "category": "account"},
    {"id": "T-102", "subject": "Invoice PDF missing VAT number",
     "body": "The March invoice PDF does not show our VAT number in the footer.",
     "status": "open", "priority": "medium", "category": "billing"},
    {"id": "T-103", "subject": "Feature request: dark mode",
     "body": "Several users asked for a dark theme in the dashboard.",
     "status": "open", "priority": "low", "category": "feature"},
    {"id": "T-104", "subject": "API returns 500 on /v2/search",
     "body": "Intermittent 500s from the search endpoint since yesterday's deploy.",
     "status": "open", "priority": "high", "category": "bug"},
    {"id": "T-105", "subject": "Question about annual plan pricing",
     "body": "A prospect asks whether the annual plan includes SSO.",
     "status": "open", "priority": "medium", "category": "sales"},
    {"id": "T-106", "subject": "Duplicate charge on card ending 4417",
     "body": "Customer was charged twice for order ORD-8821 on the same day.",
     "status": "open", "priority": "high", "category": "billing"},
    {"id": "T-107", "subject": "Export to CSV drops the notes column",
     "body": "The weekly export loses the notes field for tickets older than 30 days.",
     "status": "open", "priority": "medium", "category": "bug"},
    {"id": "T-108", "subject": "How do I invite a teammate?",
     "body": "An admin user cannot find the invite button on the team page.",
     "status": "open", "priority": "low", "category": "howto"},
    {"id": "T-109", "subject": "Webhook deliveries delayed by 10 minutes",
     "body": "Delivery logs show a consistent ten-minute lag on outbound webhooks.",
     "status": "open", "priority": "high", "category": "bug"},
    {"id": "T-110", "subject": "Refund request for cancelled subscription",
     "body": "Customer cancelled mid-cycle and asks for a pro-rated refund.",
     "status": "open", "priority": "medium", "category": "billing"},
]

Now s01_comprehensions.py exercises all three:

python
# s01_comprehensions.py — the three comprehensions, conditions, nesting, genexps.
from tickets_data import TICKETS

# --- the three comprehensions -------------------------------------------------
urgent_subjects = [t["subject"] for t in TICKETS if t["priority"] == "high"]
subject_by_id = {t["id"]: t["subject"] for t in TICKETS}
open_categories = {t["category"] for t in TICKETS if t["status"] == "open"}

print("urgent subjects:", urgent_subjects)
print("subject by id   :", subject_by_id)
print("categories      :", sorted(open_categories))

# --- conditions: `if` filters, `if/else` transforms ----------------------------
short_flags = ["short" if len(t["subject"]) < 30 else "long" for t in TICKETS]
print("length flags    :", short_flags)

# --- nested: flatten pairs of (priority, status) labels -----------------------
priority_status = [
    (p, s)
    for p in ("high", "medium", "low")
    for s in ("open", "closed")
]
print("priority x status pairs:", priority_status[:4], "...", len(priority_status), "total")

# --- generator expressions + any/all ------------------------------------------
print("any high priority:", any(t["priority"] == "high" for t in TICKETS))
print("all open        :", all(t["status"] == "open" for t in TICKETS))
total_chars = sum(len(t["subject"]) for t in TICKETS)
print("total subject chars:", total_chars)
Output8 lines
urgent subjects: ['Cannot log in after password reset', 'API returns 500 on /v2/search', 'Duplicate charge on card ending 4417', 'Webhook deliveries delayed by 10 minutes']
subject by id   : {'T-101': 'Cannot log in after password reset', 'T-102': 'Invoice PDF missing VAT number', 'T-103': 'Feature request: dark mode', 'T-104': 'API returns 500 on /v2/search', 'T-105': 'Question about annual plan pricing', 'T-106': 'Duplicate charge on card ending 4417', 'T-107': 'Export to CSV drops the notes column', 'T-108': 'How do I invite a teammate?', 'T-109': 'Webhook deliveries delayed by 10 minutes', 'T-110': 'Refund request for cancelled subscription'}
categories      : ['account', 'billing', 'bug', 'feature', 'howto', 'sales']
length flags    : ['long', 'long', 'short', 'short', 'long', 'long', 'long', 'short', 'long', 'long']
priority x status pairs: [('high', 'open'), ('high', 'closed'), ('medium', 'open'), ('medium', 'closed')] ... 6 total
any high priority: True
all open        : True
total subject chars: 333

A few things to notice:

  • The list comprehension [t["subject"] for t in TICKETS if ...] produces a list. The dict comprehension {t["id"]: t["subject"] ...} produces a dict — the part before the for is a key: value pair. The set comprehension {t["category"] ...} produces a set, so duplicates collapse — watch the output above: 10 tickets but only 6 categories, because billing and bug each appear three times. sorted() makes the print order stable anyway — sets have no guaranteed order.
  • Watch duplicate keys in dict comprehensions: if two items produce the same key, the last value silently wins — {t["id"]: t["subject"] for t in TICKETS} over a dataset with a repeated id keeps only the later row (01A.4's data has a deliberate duplicate for exactly this trap). Set comprehensions just deduplicate. If key uniqueness matters, check for duplicates first — 01A.4, 4.6 has the recipe.
  • The expression before for can be anything: t["subject"], t["id"]: t["subject"], "short" if ... else "long", (p, s).
  • The if after the for filters (decides whether to emit at all). An if/else inside the expression transforms (decides what to emit). They look similar and do different jobs — this trips up every beginner once.

1.2 Conditions: filtering and transforming#

The two positions of if are worth practising until automatic:

python
# s01b_conditions.py — filter vs transform, side by side.
from tickets_data import TICKETS

# `if` AFTER the for: keeps only matching items.
high_ids = [t["id"] for t in TICKETS if t["priority"] == "high"]

# `if/else` INSIDE the expression: every item is kept, reshaped.
labels = [
    f"{t['id']} ({t['priority']})" if t["priority"] == "high" else t["id"]
    for t in TICKETS
]

# Multiple `if`s are ANDed.
billing_open = [
    t["id"] for t in TICKETS
    if t["category"] == "billing" and t["status"] == "open"
]

print("high ids       :", high_ids)
print("labels         :", labels)
print("billing open   :", billing_open)

Run it:

bash
python3 s01b_conditions.py
Output3 lines
high ids       : ['T-101', 'T-104', 'T-106', 'T-109']
labels         : ['T-101 (high)', 'T-102', 'T-103', 'T-104 (high)', 'T-105', 'T-106 (high)', 'T-107', 'T-108', 'T-109 (high)', 'T-110']
billing open   : ['T-102', 'T-106', 'T-110']

Two subtleties:

  • You can stack conditions: if a and b works, and you can even write two if clauses (for t in xs if a if b) which is equivalent to if a and b — rarely worth the extra typing.
  • There is no else on the filter position. [x for x in xs if cond else y] is a syntax error; the else belongs inside the expression, as shown.

1.3 Nested comprehensions — and when not to#

A comprehension can have more than one for, which behaves like nested loops — the rightmost for is the inner loop:

python
# s01c_nested.py — one `for` per loop level; rightmost runs fastest.
pairs = [(p, s) for p in ("high", "low") for s in ("open", "closed")]
print(pairs)
# Equivalent to:
# pairs = []
# for p in ("high", "low"):
#     for s in ("open", "closed"):
#         pairs.append((p, s))
Output1 line
[('high', 'open'), ('high', 'closed'), ('low', 'open'), ('low', 'closed')]

The classic real-world use is flattening a list of lists:

python
matrix = [[1, 2], [3, 4], [5, 6]]
flat = [x for row in matrix for x in row]
print(flat)   # [1, 2, 3, 4, 5, 6]

1.4 Scope, the walrus operator, and readability#

Comprehensions have their own little scope in Python 3: the loop variable does not leak into the enclosing code.

python
# s02_scope_walrus.py — comprehension scope and the walrus operator.

squares = [x * x for x in range(5)]
print("squares:", squares)
try:
    print("x after comprehension:", x)
except NameError as e:
    print("x after comprehension ->", type(e).__name__, e)

# The walrus binds in the ENCLOSING scope, not the comprehension's.
filtered = [y for n in range(10) if (y := n * n) < 30]
print("filtered:", filtered)
print("y leaked into enclosing scope:", y)   # last value the walrus assigned
Output4 lines
squares: [0, 1, 4, 9, 16]
x after comprehension -> NameError name 'x' is not defined
filtered: [0, 1, 4, 9, 16, 25]
y leaked into enclosing scope: 81

Two things to take away:

  1. x is local to the comprehension — referencing it afterwards raises NameError (you'll see the full traceback in the gallery).
  2. (y := ...) is the walrus operator (assignment expression, Python 3.8+): it assigns and yields the value in one step. It is the one thing inside a comprehension that does leak — y exists after the comprehension finishes. Note y ended at 81, not 25: the walrus runs for every n, even the ones the if rejects, so it holds the last assignment (9 * 9), not the last kept value. Walruses in comprehensions are powerful but easy to misuse; reach for them when the condition needs a computed value twice, e.g. [line for line in lines if (stripped := line.strip())].

1.5 Generator expressions and any()/all()#

Swap the square brackets for parentheses and you get a generator expression — same syntax, but it produces a lazy iterator (Part 3 explains laziness properly) instead of a list. You almost always write one as an argument to a function that consumes it:

python
# s03_genexp.py — generator expressions are lazy; any/all short-circuit.

calls = []

def pred(x):
    calls.append(x)
    return x > 3

print("any(pred):", any(pred(x) for x in range(10)))
print("pred was called for:", calls)   # stopped at 4, never saw 5..9

calls.clear()
print("all(pred):", all(pred(x) for x in range(10)))
print("pred was called for:", calls)   # all() stops at the FIRST False (x=0)

# A generator expression builds nothing until iterated.
squares = (n * n for n in range(5))
print("type:", type(squares).__name__)
print("first two:", next(squares), next(squares))
print("rest       :", list(squares))    # continues where it left off
Output7 lines
any(pred): True
pred was called for: [0, 1, 2, 3, 4]
all(pred): False
pred was called for: [0]
type: generator
first two: 0 1
rest       : [4, 9, 16]

The important behaviours:

  • any() returns True at the first truthy item and all() returns False at the first falsy one — they never need to see the rest. With a genexp, the remaining items are never even computed. With a list comprehension, they would be: [pred(x) for x in range(10)] runs pred ten times before any sees the list. For expensive predicates over big data, that difference is the whole point.
  • sum, min, max, sorted, list, tuple, set, any, all, join and friends all accept genexps directly. When a genexp is the only argument, you can drop the extra parentheses: sum(x * x for x in range(10)).
  • A genexp on its own, assigned to a variable, is legal but unusual — if you want the values more than once you wanted a list; if once, feed it straight to a consumer.

Part 2: The iteration protocol — what for really does#

Every for loop in Python, over every kind of object, runs the same tiny protocol. Understanding it explains half the "weird" behaviour beginners hit — exhausted iterators, one-shot streams, StopIteration escaping where it shouldn't.

2.1 Iterables vs iterators#

Two different kinds of objects are involved:

  • An iterable is anything you can write for x in thing over, or pass to iter(). Lists, tuples, dicts, sets, strings, files, range objects — all iterables. Crucially, an iterable can produce a fresh iterator every time you ask, so you can loop over it again and again.
  • An iterator is the cursor that walks through the items one at a time. It remembers where it is. Once it reaches the end it stays exhausted — there is no rewinding.

The relationship is one-directional: every iterator is also iterable (it returns itself), but not every iterable is an iterator.

flowchart LR
    subgraph iterable ["Iterable (re-usable)"]
        L["list, tuple, dict, str, file, range"]
    end
    L -->|"iter()"| IT["Iterator (one-shot cursor)"]
    IT -->|"next()"| V["one item"]
    IT -->|"next() again"| V2["next item"]
    IT -->|"next() until empty"| S["StopIteration"]
    V --> C["for-loop body"]
    V2 --> C
    S -.->|"for-loop ends"| DONE(["loop finished"])

2.2 iter(), next() and StopIteration#

iter(x) asks an iterable for a fresh iterator. next(it) asks an iterator for its next item; when there are none left it raises StopIteration, the internal signal that means "done".

python
# s04_protocol.py — iterables vs iterators: iter(), next(), StopIteration.

my_list = [10, 20, 30]
it = iter(my_list)               # ask the iterable for an iterator
print("iter(list) ->", type(it).__name__)
print("next three :", next(it), next(it), next(it))
try:
    next(it)                     # nothing left
except StopIteration:
    print("next() on exhausted iterator -> StopIteration")

# next() with a default never raises.
it2 = iter([1])
print("next(it2)      :", next(it2))
print("next(it2, 'end'):", next(it2, "end"), "| again:", next(it2, "end"))

# iter(callable, sentinel): call the callable until it returns the sentinel.
# Classic use: pull items until a terminator/EOF marker appears.
pending = iter(["chunk-1", "chunk-2", "chunk-3"])
def read_chunk():
    return next(pending, "")        # "" once the source is exhausted

for chunk in iter(read_chunk, ""):
    print("got:", chunk)

# Strings, dicts and files are iterables too.
print("list(iter('ab')) ->", list(iter("ab")))
d = {"a": 1, "b": 2}
print("iterating a dict yields keys:", list(iter(d)))
Output10 lines
iter(list) -> list_iterator
next three : 10 20 30
next() on exhausted iterator -> StopIteration
next(it2)      : 1
next(it2, 'end'): end | again: end
got: chunk-1
got: chunk-2
got: chunk-3
list(iter('ab')) -> ['a', 'b']
iterating a dict yields keys: ['a', 'b']

Now the payoff — this is the entire secret of the for loop:

python
# s04b_desugar.py — what `for x in items:` really does, spelled out.
items = ["a", "b", "c"]

print("for-loop version:")
for x in items:
    print(" ", x)

print("manual version (same result):")
_it = iter(items)
while True:
    try:
        x = next(_it)
    except StopIteration:
        break
    print(" ", x)
Output8 lines
for-loop version:
  a
  b
  c
manual version (same result):
  a
  b
  c

The for statement is roughly iter() once, then next() until StopIteration, running the body each time. (The real implementation is a bytecode-level loop, but this is the exact semantics.) Two practical consequences:

  • break simply stops asking for more items; the iterator is abandoned wherever it was.
  • return inside a function that is iterating abandons the iterator too — which matters for generators in 3.6.

2.3 One-shot iterators#

Because an iterator remembers its position, it can only be consumed once. Ask a list for a new iterator and you can loop forever; ask the iterator itself and the second loop sees nothing:

python
# s12b_one_shot.py — iterators are single-use; iterables are not.
shared = iter(["a", "b", "c"])
print("first pass :", list(shared))
print("second pass:", list(shared))

# But the list itself is happy to vend fresh iterators:
items = ["a", "b", "c"]
print("list pass 1:", list(items))
print("list pass 2:", list(items))
Output4 lines
first pass : ['a', 'b', 'c']
second pass: []
list pass 1: ['a', 'b', 'c']
list pass 2: ['a', 'b', 'c']

Some objects blur the line: files and generators are their own iterators — iter(f) on an open file returns f itself. That is why you cannot "rewind" a file by looping it twice; you seek(0) or reopen it. Generators are covered fully in Part 3.

2.4 The helpers: enumerate, zip, zip_longest, reversed, sorted and range#

Python hands you a toolkit of functions that all return iterators (or lists, for sorted):

python
# s05_helpers.py — enumerate, zip, zip_longest, reversed, sorted, range, map/filter.
import itertools

names = ["T-101", "T-104", "T-106"]
priorities = ["high", "high", "high"]

print("--- enumerate -----------------------------------------------------")
for i, name in enumerate(names):
    print(f"{i}: {name}")
for i, name in enumerate(names, start=1):   # start= is handy for 1-based numbering
    print(f"ticket #{i}: {name}")

print("--- zip ------------------------------------------------------------")
for tid, pri in zip(names, priorities):
    print(tid, "->", pri)
print("zip stops at the SHORTEST input:",
      list(zip(range(3), ["a", "b", "c", "d", "e"])))
print("zip(*rows) transposes:",
      list(zip(*[(1, "a"), (2, "b"), (3, "c")])))

print("--- itertools.zip_longest ------------------------------------------")
for row in itertools.zip_longest(names, priorities, ["x", "y"], fillvalue="-"):
    print(row)

print("--- reversed / sorted ----------------------------------------------")
print("reversed:", list(reversed(names)))
tickets = [("T-104", 3), ("T-101", 1), ("T-106", 2)]
print("sorted by second field:", sorted(tickets, key=lambda t: t[1]))
print("sorted desc by id     :", sorted(tickets, key=lambda t: t[0], reverse=True))

print("--- range is lazy too ----------------------------------------------")
r = range(10**9)
print("type:", type(r).__name__, "| len works:", len(r), "| slice:", r[5:8])

print("--- map / filter ----------------------------------------------------")
print("map   :", list(map(str.upper, ["bug", "billing"])))
print("filter:", list(filter(lambda s: "bug" in s, ["bug report", "invoice", "debug build"])))
Output26 lines
--- enumerate -----------------------------------------------------
0: T-101
1: T-104
2: T-106
ticket #1: T-101
ticket #2: T-104
ticket #3: T-106
--- zip ------------------------------------------------------------
T-101 -> high
T-104 -> high
T-106 -> high
zip stops at the SHORTEST input: [(0, 'a'), (1, 'b'), (2, 'c')]
zip(*rows) transposes: [(1, 2, 3), ('a', 'b', 'c')]
--- itertools.zip_longest ------------------------------------------
('T-101', 'high', 'x')
('T-104', 'high', 'y')
('T-106', 'high', '-')
--- reversed / sorted ----------------------------------------------
reversed: ['T-106', 'T-104', 'T-101']
sorted by second field: [('T-101', 1), ('T-106', 2), ('T-104', 3)]
sorted desc by id     : [('T-106', 2), ('T-104', 3), ('T-101', 1)]
--- range is lazy too ----------------------------------------------
type: range | len works: 1000000000 | slice: range(5, 8)
--- map / filter ----------------------------------------------------
map   : ['BUG', 'BILLING']
filter: ['bug report', 'debug build']

Worth memorising:

  • enumerate(iterable, start=0) yields (index, item) pairs — the Pythonic replacement for C-style for (i = 0; i < n; i++). Use start=1 when the index is shown to humans.
  • zip(*iterables) yields tuples of items taken in lockstep — zip(ids, names) gives (id, name) pairs. Two classic uses: pairing parallel columns, and transposing with zip(*rows).
  • zip stops at the shortest input. That is convenient when lengths legitimately differ and a silent disaster when they should match — a bug upstream produces quietly truncated data. Since Python 3.10, zip(a, b, strict=True) raises ValueError on a length mismatch instead:
python
# tb_zip_strict.py — zip(strict=True) refuses silently-dropped items.
for a, b in zip(range(3), ["fee", "fi", "fo", "fum"], strict=True):
    print(a, b)
text
0 fee
1 fi
2 fo
Traceback (most recent call last):
  File "tb_zip_strict.py", line 2, in <module>
    for a, b in zip(range(3), ["fee", "fi", "fo", "fum"], strict=True):
                ~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
ValueError: zip() argument 2 is longer than argument 1

Rule of thumb: when two iterables should be the same length (ids and names, scores and labels), pass strict=True and let the mismatch surface immediately. When lengths may differ on purpose, use itertools.zip_longest(..., fillvalue=...) to pad the short side — see 4.1.

  • reversed(x) needs a sequence or an object defining __reversed__ (dicts qualify — reversed(d) yields keys in reverse insertion order, since 3.8) — it does not work on iterators or sets (TypeError: ... object is not reversible). For a reversed iterator, use reversed(list(it)) or just don't.
  • sorted(iterable, key=..., reverse=...) always returns a new list; x.sort() sorts in place and returns None (01A.4 covers the difference). key= is the single most useful sorting tool in Python — Part 5 is dedicated to it.
  • range is lazy: range(10**9) stores three integers, not a billion. len() and slicing work; iterating yields values on demand. Same laziness idea as generators — you will see it again in Part 3.
  • map and filter return iterators in Python 3 and are perfectly fine, but a comprehension says the same thing in one readable line: [str.upper(s) for s in names] beats list(map(str.upper, names)) for most people, and [s for s in names if "bug" in s] beats list(filter(lambda s: "bug" in s, names)) — no lambda needed. Reach for map/filter mainly inside functools.reduce-style pipelines or when the function already exists and the comprehension would be wider than the screen.

2.5 Unpacking in loops; iterating dicts, sets and files#

The for target can be any unpacking pattern, which is how you iterate "rows" of data:

python
# s06_unpack_files.py — unpacking in loops, dict/set iteration, file lines.

pairs = [("T-101", "high"), ("T-104", "medium"), ("T-106", "low")]
print("--- tuple unpacking in for --------------------------------------")
for tid, pri in pairs:
    print(f"{tid} is {pri}")

print("--- starred unpacking --------------------------------------------")
rows = [("a", 1, 2), ("b", 3, 4, 5), ("c",)]
for first, *rest in rows:
    print(first, "rest:", rest)

print("--- dict iteration -----------------------------------------------")
counts = {"bug": 3, "billing": 4, "account": 1}
for key in counts:                    # iterates KEYS
    print("key:", key)
for key, value in counts.items():     # the usual way to get both
    print(f"{key}: {value}")
for value in counts.values():
    print("value:", value)

print("--- set iteration (unordered) ------------------------------------")
seen = {"billing", "bug"}
print(sorted(seen))                   # sort when you need stable output

print("--- iterating a file line by line -------------------------------")
with open("sample_lines.txt", "w", encoding="utf-8") as f:
    f.write("ERROR disk full on db-01\nWARN  retrying request\nINFO  job done\n")

with open("sample_lines.txt", encoding="utf-8") as f:
    for lineno, line in enumerate(f, start=1):   # files yield lines, keep \n
        print(f"{lineno}: {line.rstrip()}")
Output24 lines
--- tuple unpacking in for --------------------------------------
T-101 is high
T-104 is medium
T-106 is low
--- starred unpacking --------------------------------------------
a rest: [1, 2]
b rest: [3, 4, 5]
c rest: []
--- dict iteration -----------------------------------------------
key: bug
key: billing
key: account
bug: 3
billing: 4
account: 1
value: 3
value: 4
value: 1
--- set iteration (unordered) ------------------------------------
['billing', 'bug']
--- iterating a file line by line -------------------------------
1: ERROR disk full on db-01
2: WARN  retrying request
3: INFO  job done

Rules of thumb:

  • for k, v in d.items() is how you walk a dict; bare for k in d walks keys (insertion order since Python 3.7 — guaranteed by the language now). d.values() and d.keys() exist for completeness.
  • Sets iterate in an arbitrary order — sort them (sorted(seen)) whenever output must be stable, as we did for open_categories in Part 1.
  • Unpacking a wrong number of items raises ValueError: too many values to unpack — except starred targets, which absorb the remainder (first, *rest works on any length ≥ 1).
  • A text file object is an iterator of lines including the newline — line.rstrip() or line.strip() before use. This is the mechanism behind every "process a huge file line by line" recipe in later modules.

Part 3: Generators — lazy pipelines#

A generator is an iterator you write yourself, with yield. Where a normal function computes a result and returns it once, a generator function produces its results one at a time and can pause between them — holding onto its local state while it waits.

3.1 yield: pausing a function#

Any function containing yield becomes a generator function. Calling it does not run the body — it returns a generator object. The body starts only when someone asks for the first item with next() (or a for loop), runs to the first yield, hands that value over, and pauses, keeping every local variable alive. The next next() resumes exactly where it stopped.

python
# s07_yield.py — yield pauses a function; the call returns a generator.

def countdown(n):
    while n > 0:
        yield n          # hand one value to the caller, then PAUSE here
        n -= 1
    yield "liftoff!"

gen = countdown(3)       # calling a generator function runs NOTHING yet
print("type:", type(gen).__name__)
print("first next():", next(gen))
print("second next():", next(gen))
print("for over the rest:")
for value in gen:        # resumes where it paused
    print("  got:", value)

# A generator that already ran to the end stays exhausted.
print("next after exhaustion:", next(gen, "done"))
print("list(gen) again  :", list(gen))   # empty: one-shot
Output8 lines
type: generator
first next(): 3
second next(): 2
for over the rest:
  got: 1
  got: liftoff!
next after exhaustion: done
list(gen) again  : []

Notice the order of operations: countdown(3) printed nothing — the while loop hadn't started. next(gen) ran the body up to yield n and returned 3. The for loop then consumed the rest (1, then "liftoff!"), and after the function fell off the end the generator raised StopIteration, which for translated into "loop finished".

3.2 State between yields; laziness and memory#

Because the generator keeps its locals alive between yields, it can carry state across items — a running total, a window of recent lines, a connection — without you managing it:

python
def running_max():
    best = float("-inf")
    for value in [3, 1, 9, 4, 7]:
        if value > best:
            best = value
        yield best          # emits the max SO FAR, one per input

print(list(running_max()))   # [3, 3, 9, 9, 9]

The bigger deal is laziness: a generator only computes an item when asked for it. That makes it the standard tool for processing data larger than memory — a 10 GB log file, a stream of model tokens, a corpus of documents — because at any moment it holds one item, not all of them.

Here is the same computation two ways, measured with tracemalloc (standard library, reports peak Python memory):

python
# s08_memory.py — laziness and memory: list vs generator, measured with tracemalloc.
import sys
import tracemalloc

N = 1_000_000

def squares_list(n):
    return [i * i for i in range(n)]        # builds ALL n values up front

def squares_gen(n):
    for i in range(n):
        yield i * i                          # produces one at a time

# --- sys.getsizeof: the generator object itself is tiny and constant ---------
g = squares_gen(N)
print("sizeof generator object (bytes):", sys.getsizeof(g))
next(g); next(g)
print("sizeof after two next()          :", sys.getsizeof(g), "(unchanged: it stores no items)")
print("sizeof a 3-item list             :", sys.getsizeof([1, 2, 3]))

# --- tracemalloc: peak Python memory for the same computation -----------------
def peak_for(build):
    tracemalloc.start()
    total = sum(build(N))
    _, peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()
    return total, peak

total_l, peak_l = peak_for(squares_list)
total_g, peak_g = peak_for(squares_gen)

print(f"list version      : total={total_l}  peak={peak_l:,} bytes")
print(f"generator version : total={total_g}  peak={peak_g:,} bytes")
print("same answer:", total_l == total_g)
Example output · illustrative6 lines
sizeof generator object (bytes): 208
sizeof after two next()          : 208 (unchanged: it stores no items)
sizeof a 3-item list             : 88
list version      : total=333332833333500000  peak=40,447,144 bytes
generator version : total=333332833333500000  peak=240 bytes
same answer: True

The list version materialised a million integers — about 40 MB — before sum() could even start. The generator version peaked at 240 bytes: one integer at a time, discarded as it was added. Same answer, ~170,000× less peak memory. (Measured on Python 3.14.6; your byte counts will differ slightly but the ratio is the lesson.) sys.getsizeof is shallow — it doesn't count the objects a container points to — which is why the honest measurement is tracemalloc, and why "how much memory does this really use" is a question you measure, not guess (01A.10 revisits performance measurement properly).

3.3 yield from: delegating to a sub-generator#

yield from sub inside a generator means "yield everything sub yields, in order, then continue". It is the delegation operator — the generator-equivalent of calling a function and returning its result, except items stream through instead of arriving as one value.

python
# s19_yield_from.py — yield from delegates to a sub-generator.

def inner():
    yield "a"
    yield "b"

def outer_manual():
    for x in inner():
        yield x

def outer_delegating():
    yield "start"
    yield from inner()          # hands control to inner() until it is exhausted
    yield "end"

print("manual     :", list(outer_manual()))
print("delegating :", list(outer_delegating()))

# yield from also works on ANY iterable, not just generators.
def flatten_once():
    yield from [1, 2]
    yield from (3, 4)
    yield from "ab"
print("mixed      :", list(flatten_once()))

# A generator may `return value` — it is NOT yielded; yield from captures it.
def with_report():
    yield "row-1"
    yield "row-2"
    return {"rows": 2}

def collect():
    report = yield from with_report()    # report == {"rows": 2}
    yield f"done: {report}"

print("return value:", list(collect()))
Output4 lines
manual     : ['a', 'b']
delegating : ['start', 'a', 'b', 'end']
mixed      : [1, 2, 3, 4, 'a', 'b']
return value: ['row-1', 'row-2', "done: {'rows': 2}"]

Three uses you'll see constantly:

  • Flattening pipelines: yield from stage(...) chains stages without an intermediate list — the pattern in 3.4.
  • Transparent wrappers: a generator that adds logging or filtering around another generator can yield from it and pass values straight through, including send() values (advanced; awareness level here).
  • Return values: a generator may return value — it is not yielded; it becomes StopIteration.value, which yield from surfaces as the expression's result (report = yield from sub() above). A plain for x in sub() loop silently discards it — one more reason yield from is the right delegation tool. This is also the mechanism behind return in coroutines (PEP 380).

3.4 The ticket-triage pipeline (a worked example)#

Here is the module's worked example: the whole triage flow as a lazy pipeline — each ticket flows through every stage one at a time, and nothing holds the full dataset:

flowchart LR
    R["read_tickets()<br/>yield dicts one at a time"] --> C["clean()<br/>normalise text fields"]
    C --> K["classify()<br/>add suggested_priority"]
    K --> B["itertools.batched()<br/>groups of N tickets"]
    B --> P["report<br/>Counter summary"]
python
# s09_pipeline.py — the ticket-triage generator pipeline:
#   read_tickets() -> clean() -> classify() -> batched() -> report
from collections import Counter
from itertools import islice
from tickets_data import TICKETS

try:
    from itertools import batched          # Python 3.12+
except ImportError:                        # Python 3.11: the recipe from 4.1
    def batched(iterable, n):
        it = iter(iterable)
        while batch := tuple(islice(it, n)):
            yield batch

HIGH_WORDS = ("500", "charged twice", "delayed", "cannot log in", "security", "outage")
LOW_WORDS = ("request", "how do i", "question", "feature")

def read_tickets():
    """Yield tickets one at a time, like reading lines from a file."""
    for raw in TICKETS:
        yield dict(raw)                      # a fresh copy; callers can mutate safely

def clean(ticket):
    """Normalise the fields a classifier will read."""
    ticket["subject"] = " ".join(ticket["subject"].split())
    ticket["body"] = " ".join(ticket["body"].split())
    ticket["text"] = f"{ticket['subject']} {ticket['body']}".lower()
    return ticket

def classify(ticket):
    """Attach a rule-based priority suggestion; return the ticket."""
    text = ticket["text"]
    if any(w in text for w in HIGH_WORDS):
        ticket["suggested_priority"] = "high"
    elif any(w in text for w in LOW_WORDS):
        ticket["suggested_priority"] = "low"
    else:
        ticket["suggested_priority"] = "medium"
    return ticket

def triage():
    """The whole lazy pipeline: each ticket flows through every stage."""
    for ticket in read_tickets():
        yield classify(clean(ticket))

def report(batch_size=4):
    by_priority = Counter()
    mismatches = []
    for batch in batched(triage(), batch_size):   # consume 4 tickets at a time
        for t in batch:
            by_priority[t["suggested_priority"]] += 1
            if t["suggested_priority"] != t["priority"]:
                mismatches.append((t["id"], t["priority"], t["suggested_priority"]))
        print(f"processed batch of {len(batch)}: {[t['id'] for t in batch]}")
    print("suggested priority counts:", dict(by_priority))
    print("priority mismatches     :", mismatches)

if __name__ == "__main__":
    report()          # importing this module (e.g. from an exercise) runs nothing
Output5 lines
processed batch of 4: ['T-101', 'T-102', 'T-103', 'T-104']
processed batch of 4: ['T-105', 'T-106', 'T-107', 'T-108']
processed batch of 2: ['T-109', 'T-110']
suggested priority counts: {'high': 4, 'medium': 2, 'low': 4}
priority mismatches     : [('T-105', 'medium', 'low'), ('T-110', 'medium', 'low')]

Read it as an assembly line: read_tickets() yields dicts → clean() normalises → classify() annotates → batched() regroups into tuples of 4 (the last batch is short — that's normal) → the report consumes batch by batch. Swap TICKETS for read_tickets() reading a real file line by line and the same code handles a million tickets in the same constant memory. That swap — a literal list for a file reader — is exactly what happens between lessons 01A.5 and 01A.9.

The same report written the "eager" way — tickets = list(triage()) then process — gives identical counts but holds every ticket at once. Measured at 100,000 tickets (itertools.cycle + islice to repeat the sample data):

Example output · illustrative4 lines
lazy counts : {'high': 40000, 'medium': 20000, 'low': 40000}
eager counts: {'high': 40000, 'medium': 20000, 'low': 40000} | same: True
lazy peak  : 426,732 bytes
eager peak : 42,033,611 bytes

~100× less peak memory for the identical answer. The full script is s09b_pipeline_memory.py in the lesson's runnable set.

3.5 The text chunker (a worked example)#

Chunking — splitting documents into pieces for embedding and retrieval — is owned by 05.6 (strategies) and 05.7 (advanced techniques). What matters here is the mechanics: a chunker is a generator that turns a stream of words into a stream of windows.

python
# s10_chunker.py — a tiny text chunker as a generator pipeline.
# (Real chunking strategy lives in lessons 05.6-05.7; this shows the mechanics.)

def words(text):
    yield from text.split()

def chunker(text, size=8, overlap=2):
    """Yield overlapping windows of `size` words, stepping by size-overlap."""
    window = []
    step = size - overlap          # how far each new chunk's start advances
    for word in words(text):
        window.append(word)
        if len(window) == size:
            yield window
            window = window[step:]  # drop the consumed prefix; keep the `overlap` tail
    if window:
        yield window                        # the final, shorter chunk

text = ("Our warranty covers manufacturing defects for twelve months. "
        "Damage from accidental drops is not covered. Keep your receipt. "
        "Claims must be filed within thirty days of discovery.")

for i, chunk in enumerate(chunker(text, size=8, overlap=3), start=1):
    print(f"chunk {i}: {' '.join(chunk)}")
Output5 lines
chunk 1: Our warranty covers manufacturing defects for twelve months.
chunk 2: for twelve months. Damage from accidental drops is
chunk 3: accidental drops is not covered. Keep your receipt.
chunk 4: Keep your receipt. Claims must be filed within
chunk 5: be filed within thirty days of discovery.

Notice window = window[step:] — that's the overlap: consecutive chunks share overlap words (check the boundary: chunk 1 ends for twelve months. and chunk 2 starts with exactly those three words) so a sentence split across a boundary still appears whole in one of them. Real chunkers add token counting, structure awareness (headings, tables) and boundary rules on top; the generator skeleton is identical. When you reach 05.6, Part 4 you'll recognise the shape immediately.

3.6 send(), close() and cleanup — awareness#

Generators support three methods beyond next()/for:

  • .send(value) resumes the generator and delivers value as the result of the yield expression it is paused on — the mechanism behind coroutine-style code (and, historically, yield from).
  • .close() throws GeneratorExit into the generator at its pause point; finally blocks inside it run, then it dies.
  • .throw(exc) injects an exception at the pause point (rarely used directly).
python
# s11_send_close.py — send(), close() and the accumulator pattern.

def accumulator():
    total = 0
    while True:
        value = yield total            # yield current total, receive next addend
        if value is None:
            return                      # .close() lands here
        total += value

a = accumulator()
next(a)                                 # prime it: run to the first yield (total=0)
print("send(5)  ->", a.send(5))         # resumes, adds 5, yields 5
print("send(10) ->", a.send(10))        # yields 15
print("send(-3) ->", a.send(-3))        # yields 12
a.close()                               # throws GeneratorExit inside at the yield
print("closed; further next ->", next(a, "finished"))

# close() also runs `finally` blocks inside the generator.
def polite():
    try:
        yield "working"
        yield "still working"
    finally:
        print("  [generator cleanup ran]")

p = polite()
next(p)
p.close()
Output5 lines
send(5)  -> 5
send(10) -> 15
send(-3) -> 12
closed; further next -> finished
  [generator cleanup ran]

The accumulator is the canonical send() pattern: value = yield total hands out the running total and receives the next number to add. send() only works after priming — the first next() runs the generator to its first yield; calling send(non-None) before that raises TypeError.

3.7 Infinite generators and the exhaustion bugs#

A generator that never returns is legal and useful — itertools.count() is an infinite generator of integers. The contract is: the consumer decides when to stop, usually with islice, takewhile, break, or zip against a finite iterable.

python
# s12_infinite_stream.py — infinite generators, islice, exhaustion, fake token stream.
import itertools

# --- an infinite counter: fine, as long as you only take what you need --------
for n in itertools.islice(itertools.count(10, step=5), 4):
    print("count:", n)

# --- a fake LLM token stream -----------------------------------------------
TOKENS = iter(["The", " answer", " is", " 42", ".", " Hope", " that", " helps", "."])

def token_stream():
    """Pretend this is a model streaming tokens; it pauses between each."""
    for tok in TOKENS:
        yield tok

g1 = token_stream()
print("first stream :", "".join(g1))
g2 = token_stream()
print("second stream:", "".join(g2) or "(empty — the shared TOKENS iterator was already spent)")

# --- exhaustion bug: a shared iterator is empty the second time --------------
shared = iter(["a", "b", "c"])
print("first pass :", list(shared))
print("second pass:", list(shared))

# A generator FUNCTION called again gives a FRESH generator over fresh data.
def fresh():
    yield from ["x", "y"]
print("fresh() twice:", list(fresh()), list(fresh()))
Output9 lines
count: 10
count: 15
count: 20
count: 25
first stream : The answer is 42. Hope that helps.
second stream: (empty — the shared TOKENS iterator was already spent)
first pass : ['a', 'b', 'c']
second pass: []
fresh() twice: ['x', 'y'] ['x', 'y']

The token stream is a miniature of real LLM streaming: tokens arrive one at a time, the consumer renders or processes each as it lands. 03.3 builds the real thing — SDK streams are iterators of event objects you for over, and 03.3 §8.4 is the production version of .close(). The exhaustion bug in the middle is the classic mistake: token_stream() returns a fresh generator each call, but both generators draw from the same TOKENS iterator — the second call gets nothing because the source was already consumed. Iterators are single-use all the way down; when you need repeatability, build the source inside the function (yield from ["x", "y"]) or re-create it per call.

3.8 Async iterators: a one-paragraph preview#

Everything above is synchronous: each next() blocks until the next value exists. When the values come from a network — a model streaming tokens — blocking is wasteful, and Python's answer is async for over an async iterator (__aiter__/__anext__, with async def + yield making an async generator). You will meet it properly in Module 01B; the shape is recognisably the same protocol with await sprinkled in, and 03.3, Part 10 shows it streaming from all four providers. Hold that thought — the mental model you just built transfers directly.


Part 4: itertools — the iteration toolbox#

Reference

The standard library's itertools module is a set of fast, memory-efficient iterator builders — the docs call it an "iterator algebra". Every function returns an iterator (lazy, one-shot), so they compose exactly like the generators you just wrote, but in C. You will not memorise all of them; learn the dozen below and recognise the rest.

4.1 Chaining and batching: chain, islice, batched#

python
# s13_itertools1.py — chain, islice, batched, takewhile/dropwhile, groupby, tee, pairwise.
import itertools

print("--- batched --------------------------------------------------------")
print(list(itertools.batched("ABCDEFG", 3)))       # Python 3.12+; last batch may be short
# On Python 3.11 (no itertools.batched) this line raises AttributeError; the recipe is:
def batched_311(iterable, n):
    it = iter(iterable)
    while batch := tuple(itertools.islice(it, n)):
        yield batch
print("fallback       :", list(batched_311("ABCDEFG", 3)))

print("--- chain -----------------------------------------------------------")
print(list(itertools.chain("AB", "CD", [1, 2])))    # lazily concatenates
print(list(itertools.chain.from_iterable([[1, 2], [3]])))

print("--- islice ----------------------------------------------------------")
print(list(itertools.islice(range(100), 3)))                 # first 3
print(list(itertools.islice(range(100), 10, 15)))            # a window
print(list(itertools.islice(range(100), 0, 10, 2)))          # every 2nd
Output10 lines
--- batched --------------------------------------------------------
[('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]
fallback       : [('A', 'B', 'C'), ('D', 'E', 'F'), ('G',)]
--- chain -----------------------------------------------------------
['A', 'B', 'C', 'D', 1, 2]
[1, 2, 3]
--- islice ----------------------------------------------------------
[0, 1, 2]
[10, 11, 12, 13, 14]
[0, 2, 4, 6, 8]
  • chain(*iterables) concatenates lazily — chain(a, b, c) yields everything in a, then b, then c, without copying. chain.from_iterable(list_of_lists) flattens one level, same as the comprehension [x for sub in xss for x in sub] but lazier.
  • islice(iterable, start, stop[, step]) is slicing for iterators — you cannot write it[10:15] on an iterator, but islice gives you the same window. It also works on infinite iterables, which is how you take "the first N" of count(). Indices must be non-negative — islice(it, -1) raises ValueError (there is no negative-index shorthand like lists have), and step must be positive.
  • batched(iterable, n) groups items into tuples of n — added in Python 3.12, with a strict=True option added in 3.13 that raises ValueError on a short final batch. n must be at least 1: batched(it, 0) raises ValueError: n must be at least one. On 3.11 use the five-line batched_311 recipe shown above (it is the documented equivalent). batched is the standard way to turn a stream into API-sized chunks — 03.9's batch jobs and 06.2's embedding batches both think in batches.
python
# s20_batched_strict.py — itertools.batched(strict=True), Python 3.13+.
import itertools, sys
print("python:", sys.version.split()[0])
try:
    list(itertools.batched([1, 2, 3, 4, 5], 2, strict=True))
except ValueError as e:
    print("ValueError:", e)
print("even split :", list(itertools.batched([1, 2, 3, 4], 2, strict=True)))
Output · run on Python 3.14.63 lines
python: 3.14.6
ValueError: batched(): incomplete batch
even split : [(1, 2), (3, 4)]

strict=True is for the same reason as zip(strict=True): when every batch must be full (fixed-size API payloads), a ragged tail means a bug upstream — fail loudly.

4.2 groupby, takewhile, dropwhile, tee and pairwise#

python
# (continued from s13_itertools1.py)
print("--- takewhile / dropwhile ------------------------------------------")
print(list(itertools.takewhile(lambda x: x < 5, [1, 4, 6, 3, 8])))
print(list(itertools.dropwhile(lambda x: x < 5, [1, 4, 6, 3, 8])))

print("--- groupby: input MUST be sorted by the key ------------------------")
rows = [("bug", "T-104"), ("billing", "T-102"), ("bug", "T-107"),
        ("billing", "T-106"), ("bug", "T-109")]
for cat, group in itertools.groupby(rows, key=lambda r: r[0]):
    print(cat, "->", [tid for _, tid in group])
print("--- same data, sorted first -----------------------------------------")
for cat, group in itertools.groupby(sorted(rows), key=lambda r: r[0]):
    print(cat, "->", [tid for _, tid in group])

print("--- tee --------------------------------------------------------------")
a, b = itertools.tee([1, 2, 3])
print("a:", list(a), "| b still works:", list(b))

print("--- pairwise (3.10+) --------------------------------------------------")
print(list(itertools.pairwise("ABC")))
Output16 lines
--- takewhile / dropwhile ------------------------------------------
[1, 4]
[6, 3, 8]
--- groupby: input MUST be sorted by the key ------------------------
bug -> ['T-104']
billing -> ['T-102']
bug -> ['T-107']
billing -> ['T-106']
bug -> ['T-109']
--- same data, sorted first -----------------------------------------
billing -> ['T-102', 'T-106']
bug -> ['T-104', 'T-107', 'T-109']
--- tee --------------------------------------------------------------
a: [1, 2, 3] | b still works: [1, 2, 3]
--- pairwise (3.10+) --------------------------------------------------
[('A', 'B'), ('B', 'C')]
  • takewhile(pred, seq) yields items until the predicate first fails; dropwhile skips the initial run that passes and yields the rest. Both stop checking after the first failure — takewhile(x<5, [1,4,6,3,8]) gives [1,4] and never looks at the 3 and 8 that also satisfy x<5, because 6 already broke the streak.
  • groupby(iterable, key=...) groups consecutive equal keys — it does not sort or collect globally. On unsorted input it produced five one-item "groups" above; sorted, it produced the two real groups. The docs' guidance is blunt: the input should be sorted by the same key. If you can't sort (streaming data), groupby is the wrong tool — use a dict of lists or Counter. Each group is itself an iterator that must be consumed inside the loop before advancing (the [tid for _, tid in group] does that).
  • tee(iterable, n=2) splits one iterator into n independent ones — like a physical Y-splitter. Useful when two consumers need the same stream. Two caveats from the docs: once tee'd, don't keep using the original iterable elsewhere, or it can advance without the tees knowing; and tee is not free — each tee caches items until all tees have passed them, so if one iterator races far ahead of another, memory grows with the gap. The docs' advice: if one consumer will use most of the data before another starts, list() it instead.
  • pairwise(iterable) (3.10+) yields overlapping pairs (a,b), (b,c), ... — for "compare each item to its neighbour" tasks like diffing consecutive log lines.

4.3 The combinatorics and counters: product, combinations, permutations, accumulate, count, cycle, repeat#

python
# s14_itertools2.py — product, combinations, permutations, accumulate, count, cycle, repeat.
import itertools
import operator

print("--- product (cartesian product) ------------------------------------")
for combo in itertools.product(["open", "closed"], ["high", "low"]):
    print(combo)

print("--- combinations / permutations (order matters!) ---------------------")
print("combinations of 2 from ABC:", list(itertools.combinations("ABC", 2)))
print("permutations of 2 from ABC:", list(itertools.permutations("ABC", 2)))

print("--- accumulate -------------------------------------------------------")
print("running totals:", list(itertools.accumulate([10, 20, 30, 40])))
print("running product:", list(itertools.accumulate([1, 2, 3, 4], operator.mul)))

print("--- count / cycle / repeat (all infinite or repeatable) -------------")
print("count(5) x3      :", list(itertools.islice(itertools.count(5), 3)))
print("cycle('ab') x5   :", "".join(itertools.islice(itertools.cycle("ab"), 5)))
print("repeat(7, 3)     :", list(itertools.repeat(7, 3)))
Output15 lines
--- product (cartesian product) ------------------------------------
('open', 'high')
('open', 'low')
('closed', 'high')
('closed', 'low')
--- combinations / permutations (order matters!) ---------------------
combinations of 2 from ABC: [('A', 'B'), ('A', 'C'), ('B', 'C')]
permutations of 2 from ABC: [('A', 'B'), ('A', 'C'), ('B', 'A'), ('B', 'C'), ('C', 'A'), ('C', 'B')]
--- accumulate -------------------------------------------------------
running totals: [10, 30, 60, 100]
running product: [1, 2, 6, 24]
--- count / cycle / repeat (all infinite or repeatable) -------------
count(5) x3      : [5, 6, 7]
cycle('ab') x5   : ababa
repeat(7, 3)     : [7, 7, 7]
  • product(a, b) yields the cartesian product — every pairing. product(ids, ids, ids) gives every ordered triple of ids, repeats allowed (the Cartesian power — combinations_with_replacement is the unordered cousin, covered next).
  • combinations vs permutations: combinations ignore order (AB = BA, emitted once); permutations respect it (both emitted). combinations_with_replacement allows repeats. Sizes grow fast — permutations(range(10)) is 3.6 million items; always islice or size-check first.
  • accumulate(iterable, func=+) yields running totals — prefix sums, running products, running max (max as the func). Handy for cumulative metrics.
  • count(start=0, step=1) is an infinite counter; cycle(p) repeats p forever; repeat(x[, n]) yields x forever or n times. All lazy — always bound them with islice/takewhile/zip.

Also in the module, worth recognising: compress(data, selectors) (keep items whose selector is truthy), filterfalse (the opposite of filter), dropwhile (above), starmap(func, tuples) (call func(*tuple) per row), chain.from_iterable, and the itertools recipes section of the docs — dozens of copy-paste patterns (grouper, sliding_window, roundrobin, partition, powerset) that show how the primitives compose. Check them before hand-rolling.

4.4 functools.reduce and the operator module#

Two small companions round out the toolkit:

python
# s15_reduce_operator.py — functools.reduce and the operator module.
import functools
import operator

tickets = [
    {"id": "T-101", "priority_rank": 1},
    {"id": "T-104", "priority_rank": 3},
    {"id": "T-106", "priority_rank": 2},
]

print("--- functools.reduce ------------------------------------------------")
print("sum via reduce :", functools.reduce(operator.add, [1, 2, 3, 4], 0))
print("max via reduce :", functools.reduce(max, [3, 1, 4, 1, 5]))
# reduce without a start value uses the first element as the initial value:
print("no-initialiser :", functools.reduce(operator.add, [1, 2, 3]))

print("--- operator.itemgetter / attrgetter -------------------------------")
rows = [("T-104", 3), ("T-101", 1), ("T-106", 2)]
print("sorted by field 1:", sorted(rows, key=operator.itemgetter(1)))
print("min by field 1   :", min(rows, key=operator.itemgetter(1)))

by_id = {t["id"]: t["priority_rank"] for t in tickets}
print("itemgetter on dicts:", sorted(by_id.items(), key=operator.itemgetter(1)))

print("--- methodcaller -----------------------------------------------------")
texts = ["  Bug REPORT  ", "invoice question"]
print("lower+strip:", [operator.methodcaller("strip")(t).lower() for t in texts])
Output10 lines
--- functools.reduce ------------------------------------------------
sum via reduce : 10
max via reduce : 5
no-initialiser : 6
--- operator.itemgetter / attrgetter -------------------------------
sorted by field 1: [('T-101', 1), ('T-106', 2), ('T-104', 3)]
min by field 1   : ('T-101', 1)
itemgetter on dicts: [('T-101', 1), ('T-106', 2), ('T-104', 3)]
--- methodcaller -----------------------------------------------------
lower+strip: ['bug report', 'invoice question']
  • functools.reduce(func, iterable[, initial]) folds an iterable into one value: reduce(add, [1,2,3,4], 0) = 0+1+2+3+4. It is the ancestor of sum/max/any/all — for those, use the builtins; reach for reduce only for a genuinely custom fold. Without initial, the first element becomes the accumulator — which raises TypeError on an empty iterable, a classic edge-case bug.
  • operator.itemgetter(i) returns a function that plucks field i — sorted(rows, key=operator.itemgetter(1)) replaces key=lambda r: r[1], and it's implemented in C so it's faster on big data. itemgetter("name") works on dicts too.
  • operator.attrgetter("attr") is the same for attributes — you'll use it once classes exist (01A.6); methodcaller("strip") returns a function that calls .strip() on its argument. These are the "named function" alternatives to lambdas in key= positions.

Part 5: Sorting, searching and picking — idioms that replace loops#

Deep-dive

A surprising amount of "loop through everything and track the best" code is one line with the right builtin.

python
# s16_sort_search.py — sorting and searching idioms: key=, bisect, heapq.
import bisect
import heapq

tickets = [
    {"id": "T-104", "priority": "high",   "score": 91},
    {"id": "T-101", "priority": "high",   "score": 87},
    {"id": "T-102", "priority": "medium", "score": 55},
    {"id": "T-106", "priority": "high",   "score": 78},
    {"id": "T-103", "priority": "low",    "score": 12},
]

print("--- sorted / min / max with key -----------------------------------")
by_score = sorted(tickets, key=lambda t: t["score"], reverse=True)
print("top by score:", [(t["id"], t["score"]) for t in by_score])
print("best ticket :", max(tickets, key=lambda t: t["score"])["id"])
print("worst       :", min(tickets, key=lambda t: t["score"])["id"])

rank = {"high": 0, "medium": 1, "low": 2}
urgent_first = sorted(tickets, key=lambda t: (rank[t["priority"]], -t["score"]))
print("priority then score:", [(t["id"], t["priority"]) for t in urgent_first])

print("--- heapq.nlargest ---------------------------------------------------")
print("top 2     :", [(t["id"], t["score"]) for t in
      heapq.nlargest(2, tickets, key=lambda t: t["score"])])
print("bottom 2  :", [(t["id"], t["score"]) for t in
      heapq.nsmallest(2, tickets, key=lambda t: t["score"])])

print("--- bisect on a sorted list ------------------------------------------")
scores = sorted(t["score"] for t in tickets)
print("scores:", scores)
pos = bisect.bisect_left(scores, 80)
print("first index with score >= 80:", pos, "->", scores[pos])
bisect.insort(scores, 84)
print("after insort(84):", scores)
Output12 lines
--- sorted / min / max with key -----------------------------------
top by score: [('T-104', 91), ('T-101', 87), ('T-106', 78), ('T-102', 55), ('T-103', 12)]
best ticket : T-104
worst       : T-103
priority then score: [('T-104', 'high'), ('T-101', 'high'), ('T-106', 'high'), ('T-102', 'medium'), ('T-103', 'low')]
--- heapq.nlargest ---------------------------------------------------
top 2     : [('T-104', 91), ('T-101', 87)]
bottom 2  : [('T-103', 12), ('T-102', 55)]
--- bisect on a sorted list ------------------------------------------
scores: [12, 55, 78, 87, 91]
first index with score >= 80: 3 -> 87
after insort(84): [12, 55, 78, 84, 87, 91]

The patterns:

  • key= is the whole game. sorted(tickets, key=lambda t: t["score"], reverse=True), max(..., key=...), min(..., key=...) — the key function is applied once per item and decides the ordering, so you never write comparison loops. Tuples as keys give multi-level sorts for free: (rank[priority], -score) sorts by priority first, then descending score inside each priority (the minus flips just that field — a trick worth remembering).
  • heapq.nlargest(n, it, key=...) / nsmallest give the top/bottom N without a full sort — O(n log k) instead of O(n log n), and they accept any iterable including generators. For "top 10 results" this is the idiom; for k close to n, sorted is simpler.
  • bisect maintains sorted order on a sorted list: bisect_left finds the insertion point in O(log n), insort inserts keeping order. The hard requirement — the list must already be sorted by the same criterion, and bisect has no key= on older versions (a key parameter was added in 3.10). For dicts you'd bisect on a parallel key list or use key=.
  • heapq beyond nlargest: heappush/heappop maintain a priority queue — awareness level here; it's the right tool for streaming top-k over huge inputs.
  • min/max need a non-empty iterable — max([]) raises ValueError: max() iterable argument is empty. When empty is a legitimate case, pass default=: max(scores, default=-1) (it composes with key= too). This is the builtin answer to the reduce empty-input trap in 4.4 — prefer the builtin whenever one fits.

Common mistakes#

The gallery — each snippet below is real, deterministic stdlib Python:

Late binding in comprehension lambdas. A lambda built inside a comprehension captures the variable, not the value — so every lambda sees the final x:

python
# g_late_binding.py — lambdas in a comprehension capture the VARIABLE.
funcs = [lambda: x for x in range(3)]
print("all see last x:", [f() for f in funcs])

fixed = [(lambda x=x: x) for x in range(3)]
print("default-arg fix:", [f() for f in fixed])
Output2 lines
all see last x: [2, 2, 2]
default-arg fix: [0, 1, 2]

The default argument is evaluated once, when the lambda is created — that is the fix. The general fix for any closure over a loop variable is a factory function (def make(n): return lambda: n). The same trap bites decorators and callbacks built in loops, not just comprehensions.

Generator side effects run in pull order, not build order. Composing generators executes nothing; each next() pulls one item through every stage:

python
# g_sidefx.py — generator side effects run in pull order, not build order.
log = []

def produce():
    for i in range(3):
        log.append(f"produced {i}")
        yield i * 10

def consume(gen):
    for v in gen:
        log.append(f"consumed {v}")
        yield v

pipeline = consume(produce())       # builds the pipeline; runs nothing
print("after build:", log)
print("first next():", next(pipeline), "| log:", log)
print("rest        :", list(pipeline))
print("final log   :", log)
Output4 lines
after build: []
first next(): 0 | log: ['produced 0', 'consumed 0']
rest        : [10, 20]
final log   : ['produced 0', 'consumed 0', 'produced 1', 'consumed 10', 'produced 2', 'consumed 20']

Nothing logged at build time; produced and consumed interleave one-for-one as the consumer pulls. If your pipeline "doesn't run", you forgot to iterate it — and if side effects look oddly ordered, this interleaving is why.

The comprehension variable doesn't exist outside. It lives in the comprehension's hidden scope:

python
# tb_comp_scope.py — the loop variable of a comprehension does not leak.
squares = [x * x for x in range(5)]
print(squares)
print(x)
text
[0, 1, 4, 9, 16]
Traceback (most recent call last):
  File "tb_comp_scope.py", line 4, in <module>
    print(x)
          ^
NameError: name 'x' is not defined

StopIteration raised inside a generator becomes RuntimeError. Since PEP 479 (default in 3.7) Python converts it so the real cause isn't swallowed — return to end a generator, never raise StopIteration:

python
# tb_stopiteration_in_gen.py — raising StopIteration inside a generator is a RuntimeError.
def bad():
    yield 1
    raise StopIteration("done")

for x in bad():
    print(x)
text
1
Traceback (most recent call last):
  File "tb_stopiteration_in_gen.py", line 4, in bad
    raise StopIteration("done")
StopIteration: done

The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "tb_stopiteration_in_gen.py", line 6, in <module>
    for x in bad():
             ~~~^^
RuntimeError: generator raised StopIteration

next() past the end raises a bare StopIteration. It is an internal control-flow signal, not a value — catch it deliberately or use next(it, default):

python
# tb_next_exhausted.py — next() past the end raises StopIteration.
it = iter([1, 2])
next(it); next(it)
next(it)
text
Traceback (most recent call last):
  File "tb_next_exhausted.py", line 4, in <module>
    next(it)
    ~~~~^^^^
StopIteration

batched(it, 0) is a ValueError. The batch size must be at least 1 — a zero (or negative) size is a bug, not an empty result:

python
# tb_batched_zero.py — itertools.batched requires n >= 1.
import itertools
list(itertools.batched([1, 2, 3], 0))
text
Traceback (most recent call last):
  File "tb_batched_zero.py", line 3, in <module>
    list(itertools.batched([1, 2, 3], 0))
         ~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^
ValueError: n must be at least one

Two more traps worth naming even though the parts above already show the fixes: the giant list comprehension — [expensive(x) for x in huge] materialises every result before sum/any/max sees item one; the genexp form computes lazily (1.5, exercise 10) — and the exhausted iterator — a one-shot iterator shared between two consumers is empty for the second (2.3, 3.7).


Common misconceptions#

Misconception Reality
"A comprehension is always faster than a loop." Marginally, sometimes — the win is readability and one-pass transform+filter, not raw speed. The real performance lever is laziness (genexps, generators), not brackets vs append.
"The loop variable of a comprehension leaks, like a JS var." It doesn't — it is local to the comprehension's hidden scope (NameError afterwards). The walrus (y := ...) is the exception: it binds in the enclosing scope.
"for x in d gives me the values." It gives keys. Use d.items() for pairs or d.values() for values.
"An iterator can be looped over twice." No — it is exhausted after one pass. Ask the iterable for a fresh iterator each time (iter(list) again), or materialise with list().
"zip(a, b) pairs everything up." It stops at the shortest input, silently dropping the tail of longer ones. Use strict=True (3.10+) when lengths must match, zip_longest when padding is intended.
"yield returns a value like return." yield suspends the function and hands one value to the caller; the function resumes on the next next(). return ends it for good.
"Calling a generator function runs it." It returns a generator object instantly; the body doesn't start until the first next().
"A generator holds all its results in memory." The opposite — it holds one item at a time plus its paused state. That is why it streams files too big for RAM.
"groupby collects all items with the same key." It groups only consecutive equal keys — sort by the key first, or use a dict/Counter.
"itertools.batched is available everywhere." It is 3.12+ (strict= is 3.13+). On 3.11 use the five-line islice recipe in 4.1.
"send()/close() are needed to use generators." for/next() cover ~99% of use. .close() matters when the generator holds a resource (file, connection) — see 03.3, 8.4.
"Raising StopIteration inside a generator is fine." Since Python 3.7 (PEP 479) it becomes RuntimeError: generator raised StopIteration. Just return to end a generator.
"map/filter are old-fashioned; comprehensions replaced them." They didn't — they coexist. Comprehensions are usually clearer, but map/filter are still iterators and fine inside larger pipelines.

Key takeaways#

  • Comprehensions build lists, dicts and sets in one expression: [expr for x in xs if cond]. if after the for filters; if/else inside the expression transforms. Keep nesting to two fors max — beyond that, write the loop.
  • Comprehension loop variables don't leak; the walrus (y := ...) does — and it assigns on every iteration, kept or not.
  • Generator expressions (expr for x in xs) are lazy and feed sum/any/all/max directly; any/all short-circuit, so they never compute the tail.
  • The iteration protocol: iter(x) gets an iterator, next(it) gets items until StopIteration. for is exactly that loop. Iterators are one-shot; iterables vend fresh ones.
  • Helpers worth memorising: enumerate(start=), zip (+strict=True since 3.10), itertools.zip_longest, reversed (sequences only), sorted(key=), lazy range, and map/filter (usually beaten by comprehensions).
  • Generators (yield) pause a function mid-flight, keep their locals, and produce items lazily — constant memory for unbounded input. yield from delegates; send/close/throw are the advanced trio (.close() runs finally cleanup).
  • Pipelines compose: read → clean → classify → batched → report is four small generators and measured ~100× less peak memory than materialising the list.
  • itertools is the C-speed toolbox: chain, islice, batched (3.12+, strict 3.13+), groupby (sort first!), takewhile/dropwhile, tee, pairwise, product/combinations/permutations, accumulate, count/cycle/repeat.
  • functools.reduce folds to one value (prefer sum/max/any when they fit); operator.itemgetter/attrgetter/methodcaller are fast key= functions.
  • Sorting idioms: sorted/min/max with key= (tuple keys = multi-level sorts), heapq.nlargest/nsmallest for top-k, bisect/insort on sorted lists.
  • Async iteration (async for, async generators) is the same protocol with await — Module 01B owns it; 03.3, Part 10 shows it live.

Terms introduced in this lesson#

Term One-line definition
Comprehension A single expression that builds a collection by transforming/filtering an iterable ([x for x in xs if c])
Generator expression A comprehension with parentheses instead of brackets — produces a lazy iterator, not a list
Iterable Any object for/iter() accepts; can vend a fresh iterator each time (list, dict, str, file, range)
Iterator A one-shot cursor over an iterable's items; remembers position, raises StopIteration at the end
Iteration protocol The iter()/next()/StopIteration contract every for loop runs
StopIteration The exception an exhausted iterator raises; for catches it to end the loop
Generator An iterator produced by a function containing yield; pauses and resumes with its state intact
Generator function A def containing yield; calling it returns a generator without running the body
yield Suspends the generator, emits one value, resumes on next next()
yield from Delegates: yields everything a sub-iterator produces, then continues
Laziness Computing items only when requested — constant memory for unbounded input
send() / .close() / .throw() Generator methods: inject a value at the yield, end it (running finally), inject an exception
GeneratorExit The exception .close() throws into a paused generator
itertools The standard library's iterator-building toolkit (chain, islice, batched, groupby, …)
itertools.batched Groups an iterable into tuples of n (3.12+; strict= in 3.13+)
itertools.islice Iterator-safe slicing: islice(it, start, stop, step)
itertools.groupby Groups consecutive equal keys — input must be sorted by the key
itertools.tee Splits one iterator into n independent iterators
itertools.pairwise Yields overlapping adjacent pairs (a,b), (b,c), … (3.10+)
itertools.accumulate Yields running totals (prefix sums) with an optional function
functools.reduce Folds an iterable to one value via a binary function
operator.itemgetter / attrgetter C-speed key functions: pluck index/key or attribute
key= function The callable sorted/min/max/heapq apply to each item to decide order
bisect / insort O(log n) insertion-point search and sorted-list insert
heapq.nlargest / nsmallest Top/bottom-k of any iterable without a full sort
zip(strict=True) zip variant (3.10+) that raises ValueError on length mismatch
zip_longest zip variant that pads shorter iterables with fillvalue
Late binding A closure captures the variable, not the value — lambdas built in a loop all see the final binding
Async iterator The __aiter__/__anext__ counterpart used by async for (preview; Module 01B)

All terms are also collected in the glossary.


Exercises#

Work through these in order — they build on each other and assume the lesson's files exist: tickets_data.py (Part 1) and s09_pipeline.py (3.4, for exercise 12's stages). Solutions are inside the collapsible blocks; try each before peeking. If you run the solutions in one session, earlier imports carry over — exercise 13 uses the itertools imported in exercise 7's solution.

  1. Comprehensions (1.1): Build a dict mapping each open ticket's id to its category, using a dict comprehension. Expected keys: all ten T-1xx ids.
Solution
python
open_by_id = {t["id"]: t["category"] for t in TICKETS if t["status"] == "open"}
print(open_by_id)
Output1 line
{'T-101': 'account', 'T-102': 'billing', 'T-103': 'feature', 'T-104': 'bug', 'T-105': 'sales', 'T-106': 'billing', 'T-107': 'bug', 'T-108': 'howto', 'T-109': 'bug', 'T-110': 'billing'}
  1. Filter vs transform (1.2): Produce (id, flag) pairs where flag is "long" when len(subject) >= 30 else "short" — a transform, so every ticket appears. Print the first four.
Solution
python
flags = [(t["id"], "long" if len(t["subject"]) >= 30 else "short") for t in TICKETS]
print(flags[:4])
Output1 line
[('T-101', 'long'), ('T-102', 'long'), ('T-103', 'short'), ('T-104', 'short')]
  1. Nested comprehensions (1.3): Flatten groups = [["T-101", "T-102"], ["T-103"], ["T-104", "T-105", "T-106"]] with a nested comprehension, then rewrite it as a plain nested loop and confirm identical output.
Solution
python
groups = [["T-101", "T-102"], ["T-103"], ["T-104", "T-105", "T-106"]]
flat = [tid for g in groups for tid in g]

flat_loop = []
for g in groups:
    for tid in g:
        flat_loop.append(tid)

print(flat)
print("identical:", flat == flat_loop)
Output2 lines
['T-101', 'T-102', 'T-103', 'T-104', 'T-105', 'T-106']
identical: True
  1. Walrus and scope (1.4): Predict, then run: res = [y for n in range(6) if (y := n * n) < 20] — what is res, and what is y afterwards? Explain why y is not the last kept value.
Solution
python
res = [y for n in range(6) if (y := n * n) < 20]
print(res, "| y =", y)
Output1 line
[0, 1, 4, 9, 16] | y = 25

y is 25 because the walrus assigns for every n (0–5), including n=5 whose 25 < 20 fails the filter — the assignment runs before the comparison rejects the item. The last kept value was 16 (n=4), but y holds the last assigned value.

  1. Generator expressions (1.5): Using genexps rather than list comprehensions: compute the total subject characters, the longest subject length, and the id of a longest subject — max over (length, id) tuples works because tuples compare element-wise. Where does laziness actually save work here, and where can't it?
Solution
python
print("total subject chars:", sum(len(t["subject"]) for t in TICKETS))
print("longest length    :", max(len(t["subject"]) for t in TICKETS))
best_len, best_id = max((len(t["subject"]), t["id"]) for t in TICKETS)
print("longest id        :", best_id, f"({best_len} chars)")
Output3 lines
total subject chars: 333
longest length    : 41
longest id        : T-110 (41 chars)

sum and max consume the genexp one item at a time — no intermediate list of lengths is built, and max keeps only the single best tuple. The (length, id) tuple works because tuples compare element-wise: longest wins, ties break on the id. Laziness pays off when the source is lazy — point these same expressions at a file-backed generator and nothing is materialised; over TICKETS, already a list in memory, the only saving is the small temporary list a comprehension would have built.

  1. The protocol (2.2): Write first_two(it) returning a list of the first two items of an iterator, using next(it, None) so short iterators don't raise. Test on iter([7, 8, 9]) and iter([]).
Solution
python
def first_two(it):
    return [next(it, None), next(it, None)]

print(first_two(iter([7, 8, 9])), first_two(iter([])))
Output1 line
[7, 8] [None, None]

The default None makes next total — no StopIteration can escape.

  1. zip safety (2.4): You have ids (10 items) and a priority list that accidentally has 11. Show what zip(..., strict=True) does, then fix the pairing two ways: truncate deliberately, and pad with zip_longest.
Solution
python
import itertools

ids = [t["id"] for t in TICKETS]
pri = ["high"] * len(TICKETS)

try:
    list(zip(ids, pri + ["extra"], strict=True))
except ValueError as e:
    print("ValueError:", e)

print("truncated  :", list(zip(ids, pri + ["extra"]))[:2], "...")
print("padded     :", list(itertools.zip_longest(ids[:2], pri[:1] + ["?"], fillvalue="-")))
Output3 lines
ValueError: zip() argument 2 is longer than argument 1
truncated  : [('T-101', 'high'), ('T-102', 'high')] ...
padded     : [('T-101', 'high'), ('T-102', '?')]

strict=True surfaced the bug; zip alone would have silently used only the first 10 pairs.

  1. enumerate (2.4): Print the first three tickets numbered from 1 in the form 1. T-101.
Solution
python
for n, t in enumerate(TICKETS[:3], start=1):
    print(f"{n}. {t['id']}")
Output3 lines
1. T-101
2. T-102
3. T-103
  1. yield (3.1): Write evens(n) — a generator yielding 0, 2, 4, … below n — and take the first five with islice (don't consume all of a large n).
Solution
python
import itertools

def evens(n):
    for i in range(n):
        if i % 2 == 0:
            yield i

print(list(itertools.islice(evens(10**9), 5)))
Output1 line
[0, 2, 4, 6, 8]

islice stops the generator after five items — the billion-iteration loop never runs.

  1. Laziness (3.2): Explain why sum(i * i for i in range(10**8)) completes in seconds with tiny memory, while sum([i * i for i in range(10**8)]) would need gigabytes. Verify the small case: sum(i*i for i in range(100)).
Solution
python
print("sum squares 0..99 :", sum(i * i for i in range(100)))
Output1 line
sum squares 0..99 : 328350

The genexp yields one square at a time; sum adds it and drops it — peak memory is one integer, and the whole computation finishes in seconds. The list comprehension must build all 100 million squares (each a distinct int object plus a pointer) before sum starts — roughly 3–4 GB — which is both slower and enough to exhaust memory on smaller machines.

  1. yield from (3.3): Write flatten(nested) that yields every item of every sub-list, using yield from — no explicit inner loop.
Solution
python
def flatten(nested):
    for sub in nested:
        yield from sub

print(list(flatten([[1, 2], [3], [4, 5, 6]])))
Output1 line
[1, 2, 3, 4, 5, 6]
  1. Pipeline stage (3.4): Add a stage to the triage pipeline that drops tickets with status == "test" before classification, and count what remains. (All sample tickets are "open", so the count is unchanged — the point is where the stage slots in.)
Solution
python
from s09_pipeline import read_tickets, clean, classify

def triage_active():
    for ticket in read_tickets():
        if ticket["status"] == "test":
            continue                          # drop before doing any work
        yield classify(clean(ticket))

active = list(triage_active())
print(len(active), "tickets kept")
Output1 line
10 tickets kept

The continue sits between read_tickets() and clean() — test tickets never pay for cleaning or classifying. In a real pipeline this stage would sit wherever the filter belongs; order matters for cost.

  1. itertools (4.2): Group the tickets by category using groupby correctly — print each category and its count. What goes wrong if you forget to sort?
Solution
python
import itertools

by_cat = sorted(TICKETS, key=lambda t: t["category"])
for cat, grp in itertools.groupby(by_cat, key=lambda t: t["category"]):
    print(cat, len(list(grp)))
Output6 lines
account 1
billing 3
bug 3
feature 1
howto 1
sales 1

Without sorted(...), groupby sees the categories in ticket order (account, billing, feature, bug, sales, billing, bug, howto, bug, billing) and emits a separate "group" every time the key changes — you'd get ~10 one-item groups with billing and bug appearing three times each. groupby groups consecutive equals only.

  1. Sorting idioms (5.1): Sort tickets by category ascending, then by descending subject length within each category. Print the top three (id, category) pairs. Then use heapq.nlargest to get the two longest body fields without sorting everything.
Solution
python
import heapq

ranked = sorted(TICKETS, key=lambda t: (t["category"], -len(t["subject"])))
print([(t["id"], t["category"]) for t in ranked[:3]])
print("longest bodies:", [(t["id"], len(t["body"])) for t in
      heapq.nlargest(2, TICKETS, key=lambda t: len(t["body"]))])
Output2 lines
[('T-101', 'account'), ('T-110', 'billing'), ('T-106', 'billing')]
longest bodies: [('T-101', 87), ('T-107', 71)]

The tuple key (category, -len(subject)) sorts by category first; the minus flips only the second field to descending. nlargest scans once and keeps a size-2 heap — no full sort.

  1. Infinite generators (3.7): Write fib() — an infinite Fibonacci generator (0, 1, 1, 2, 3, 5, …) — and take the first ten with islice. Why can't you list(fib())?
Solution
python
import itertools

def fib():
    a, b = 0, 1
    while True:
        yield a
        a, b = b, a + b

print(list(itertools.islice(fib(), 10)))
Output1 line
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34]

fib() never returns, so list(fib()) would try to consume an infinite iterator and never finish (it would also exhaust memory as the list grows). islice stops after ten and simply stops asking — the generator is left suspended, not closed by islice. Here nothing refers to it afterwards, so CPython closes it when the object is freed; a generator that holds a file or connection should be closed explicitly (3.6).


Where you'll use this in the AI path#

Skill from this lesson Where it shows up later
Iterating an SDK stream one event at a time; closing it early 03.3, 4.1 (streams are iterators) and 8.4 (close() and connection leaks)
async for over token streams 03.3, Part 10; async proper in Module 01B
Reading/writing JSONL line by line for batch jobs 03.9, Part 6 (batch APIs are JSONL pipelines) and 01A.9 (JSONL files)
batched/islice for fixed-size payloads 03.9, Part 11 and 06.2, 2.3 (token-aware batching)
Generator chunker → embedding pipeline 05.6, Part 4, 05.7, and 06.2, Part 4
sorted/min/max/heapq/bisect on results Evaluation and ranking everywhere — e.g. 06.2 order preservation, Module 10A metrics
Iterable/Iterator in type hints 01A.10 teaches the annotations; SDK signatures you read in 03.1 use them

Check yourself#

  1. What is the difference between an iterable and an iterator?
  2. What does for x in items: do, step by step, at the protocol level?
  3. Why does the second list(shared) in 2.3 print [] while the second list(items) prints the items again?
  4. In [expr for x in xs if cond], what do the two if positions do differently?
  5. Why does y end up 81 (not 25) in the walrus example of 1.4?
  6. When does any()/all() save work compared to a list comprehension?
  7. zip(ids, names) silently drops data — when is that a feature and when is it a bug? What's the fix?
  8. Why is itertools.batched unavailable on Python 3.11, and what replaces it?
  9. groupby returned five one-item groups on unsorted input. What single change fixes it, and why?
  10. A generator function is called but nothing happens. Why?
  11. In the memory demo, why did the generator version peak at ~240 bytes while the list version peaked at ~40 MB — and what does sys.getsizeof fail to show?
  12. Your pipeline's report() stage gets a StopIteration traceback deep inside a helper. What's the likely cause and the fix?
  13. When would you choose heapq.nlargest(10, stream) over sorted(stream)[-10:]?
  14. send()/close() — which everyday generator use cases actually need .close()?

Further resources#


← 01A.4 — Core Data Structures: Lists, Tuples, Dictionaries and Sets | Module 01A overview | 01A.6 — Classes, Dataclasses and Enums →

Esc
02.2Tokens and TokenizationHow LLMs Work · 21k wordsLesson
02.3EmbeddingsHow LLMs Work · 18k wordsLesson
07Retrieval-Augmented Generation (RAG)11 lessons · Everyone who will build LLM features that must answer from knowledge the model doesn't have in its weights: internal handbooks and help centres, contracts, ticket histories, product docs, or any corpus that changes faster than a training run. The module covers the full RAG stack — architecture, retrieval strategy, query understanding, grounded generation, citations, conversation, managed services, advanced patterns, evaluation, debugging and production operation — and shows where each major provider's managed retrieval and citation features fit (OpenAI, Anthropic, Google Gemini and OpenRouter). All code is Python.Overview
08E.1The Model Context Protocol (MCP)Protocols and Extensibility · 12k wordsLesson
↑ ↓ navigate↵ openesc close