▚ The AI Engineer's Field Manual
Appendix A1 · Before Module 00

Python Fundamentals — The Prerequisite Primer

"You already know how to program. This is the six-hour bridge so Python stops being the thing you're translating in your head."

~6 hours For: engineers fluent in another language, or rusty Python Course-ready when the lab passes

01 · The hookWhy a Strong Engineer Bounces Off Module 01

The Python you need before the rest of the course: what a name really points at, the idioms you will read every day, and the two facts about the runtime that explain most performance surprises.

Field report · Course feedback channel

"Nine years of TypeScript. I've shipped event loops, generics, decorators-by-another-name. I opened Module 01 feeling confident — and the third code block was async def summarize(client: httpx.AsyncClient, ticket: str) -> str: sitting directly on top of {t.id: t.text for t in tickets}.

I understand async. I understand type annotations. I understand map-with-a-condition. But five unfamiliar spellings of things I already knew landed in the same ten lines, and my brain rendered the whole page as noise.

I closed the tab and told myself I'd come back later. That was three weeks ago."

— Marcus O., Staff Engineer (TypeScript), on why he stalled

Nothing in that code block is hard. async def is async function. The type hints are TypeScript annotations with the colon moved. The curly-brace thing is a dict comprehension — a map and a filter wearing one outfit.

Marcus bounced not because the ideas were new but because five pieces of surface syntax arrived at once, each costing a little translation effort, and the total overran his working memory.

That's a syntax problem, not an ability problem — and syntax problems have a cheap, permanent fix: one focused pass, done before the concepts start stacking. This appendix is that pass. Finish it and Module 01 will feel natural.

Before we start fixing spellings, look at exactly what landed on Marcus, next to the thing he already knew. Every row below is a translation he could have done in a second on its own. Five of them arrived inside the same ten lines, and that pile-up is the whole of the problem.

1 FIVE SPELLINGS OF FIVE THINGS HE ALREADY KNEW what Module 01 put on the screen what he writes every working day async def summarize(...) async function summarize(...) client: httpx.AsyncClient client: HttpClient (a parameter type) -> str : string (the return type) {t.id: t.text for t in tickets} Object.fromEntries(tickets.map(t => [t.id, t.text])) for t in tickets for (const t of tickets) 2 WHAT THE PILE-UP COST opened Module 01 reached the third code block closed the tab nine years of confidence five translations at once three weeks and counting still closed when he wrote in
Fig. A1.0b — Marcus's ten lines, unpacked: five unfamiliar spellings of five familiar ideas, arriving in the same screenful, and the three weeks that followed.
  1. The five spellings. Read the rows left to right. Each Python spelling on the left is the same operation as the one on the right, which Marcus writes without thinking. Not one of them is a new idea. The fourth row is the only one that even changes shape, and it is still a map over a list.
  2. The pile-up. One translation costs a second of attention. Five of them, in the same screenful, cost more attention than anyone has spare while also learning what the code is for. That is why a confident engineer closed the tab, and why the cure is to meet the five spellings once, on their own, before any concept rides on them.

Honest prerequisite check: this appendix assumes you already program fluently in some language — it moves fast and skips "what is a variable". If you're new to programming itself, do the official Python tutorial or Automate the Boring Stuff first (both free), then come back. No shame in it — this page will still be here, and it'll go three times faster.

02 · The rosetta stoneThe Same Ten Operations, Three Languages

Marcus lost three weeks to ten lines. Before we repair any single line, he needs the map that says how much of Python he already owns, which is about nine tenths of it under different spellings. This section is that map: ten operations he performs every day, in his language and in Python, side by side. The habit being replaced here is the silent translation step, reading def and thinking function. Seeing both spellings together once is cheaper than meeting them one at a time in the middle of a lesson about something else.

You already know this

You know roughly 90% of Python already — you just know it under different spellings. The table below is the whole translation layer: ten operations you perform daily, side by side. Skim your column, then read Python's. Everything after this section is the remaining 10% — the parts Python does differently, not just differently-spelled.

The syntax rosetta — same operation, three languages (Python 3.12)
OperationJS / TSJavaPython
Variableconst n = 3;int n = 3;n = 3
Functionfunction f(x: number): number { return x * 2; }int f(int x) { return x * 2; }def f(x: int) -> int: return x * 2
Classclass User { constructor(name) { this.name = name; } }class User { User(String name) { this.name = name; } }class User: then def __init__(self, name): self.name = name
Filter + mapxs.filter(x => x > 0).map(x => x * 2)xs.stream().filter(x -> x > 0).map(x -> x * 2).toList()[x * 2 for x in xs if x > 0]
Dict lookup w/ defaultm.get(k) ?? 0m.getOrDefault(k, 0)d.get(k, 0)
String interpolation`p95 is ${ms}ms`String.format("p95 is %dms", ms)f"p95 is {ms}ms"
Null checkif (x == null)if (x == null)if x is None:
Error handlingtry {…} catch (e) {…} finally {…}try {…} catch (IOException e) {…} finally {…}try: / except ValueError as e: / finally:
Importimport { thing } from "./mod"import com.acme.Thing;from mod import thing
Iterationfor (const x of xs)for (var x : xs)for x in xs:

Three global rules the table implies, worth stating once.

The first of those three rules is the one that looks strangest in a screenshot, so here it is drawn once. The same tiny function, in braces and in indentation, with an arrow from each piece of punctuation to the thing that replaced it.

1 BRACES MARK THE BLOCK 2 A COLON OPENS IT, THE INDENT IS IT function f(x) {     if (x > 0) {         return x * 2;     }     return 0; } def f(x):     if x > 0:         return x * 2     return 0 the opening brace becomes the colon the closing brace becomes the dedent 6 lines · 2 brace pairs · 2 semicolons 4 lines · 0 brace pairs · 0 semicolons 3 the dashed bars are the bodies: same two blocks, one marked by braces, one by depth
Fig. A1.0c — Indentation is the block syntax: the same function loses two brace pairs and two semicolons, and nothing else changes.
  1. The braces version. The dashed bar on the left runs from the opening brace to the matching closing brace. That bar is the function body, and the compiler finds it by counting braces. Your indentation is a courtesy to human readers; the machine ignores it.
  2. The Python version. The dashed bar on the right runs down the indented lines. That bar is the same body, and now the machine reads the indentation itself. A colon ends the line that opens a block, every time: def, if, for, while, try, with, class.
  3. What it buys and what it costs. Four lines instead of six, and no closing brace to lose in a merge. The cost is that a wrong indent is a real change in meaning, so the editor's four-space rule matters. Python 3 refuses to run a file that mixes tabs and spaces ambiguously, so the classic horror story cannot happen silently.

03 · Core PythonValues & Collections — Four Containers, Four Jobs

The rosetta table handed Marcus back the nine tenths he already knew. The remaining tenth starts here, with the four containers that every line of course code moves data through. The habit being replaced is reaching for one growable array for everything: Python asks you to choose between four, and the choice tells the next reader what you promised. This section also carries the single fact behind four of the five traps in section 10, and it is not about containers at all: a name is a pointer, not a box.

Python ships four workhorse collections, and course code uses all four deliberately. list is your resizable array (ArrayList, JS array). tuple is a fixed-shape, immutable record — the "returns two things" type, and the only sequence you can use as a dict key. dict is your hash map, and it's the load-bearing structure of the entire AI stack: every JSON payload, every API response, every config is a dict. set is membership and uniqueness at O(1) — dedupe and "have I seen this?" checks.

Look values up by a key? yes dict · {"key": value} no Only membership / uniqueness? yes set · {"a", "b"} no Fixed-shape record, never grows? yes tuple · (3.5, 7.2) no Ordered, growable, dupes fine default list · ["a", "b"] 1 2 3 4
Fig. A1.1 — Choosing a collection: ask the three questions in order; list is the default when none of them says otherwise.
  1. dict — you look things up by name. Ask this question first, because it is the one that changes your code the most. Every JSON body, every API reply and every config file in this course arrives as a dict. Lookup by key costs the same whether the dict holds ten items or ten million.
  2. set — you only care whether something is in there. A set has no order and no duplicates. Use it for "have I seen this id?" and for removing repeats in one call. The tour script builds {"p50", "p95", "p50"} and gets two members, not three.
  3. tuple — a record whose shape never changes. A point, a pair of return values, a row. Because it cannot change, it can be hashed, which is what lets a tuple be a dict key. Choosing one is a message to the next reader: this shape is fixed.
  4. list — everything else. Ordered, growable, duplicates welcome. It is the default, and the accented box says so. If you cannot answer yes to any of the three questions above, stop thinking and write a list.

The table below shows twelve lines you have not been taught yet. That is on purpose. Guess first, then check. Every line is explained in full over the next seven sections, and the step-by-step list above each script walks it again.

Sharpen your pencil

Below are twelve lines lifted from the tour scripts on this page, starting with collections_tour.py, the file you are about to read. Three are annotated for you. In the blank rows, write what you think each line does, in plain English, before you open the answers. Wrong guesses are welcome; they are the point of the exercise.

head, *tail = values
print(values[1:3])print the items at positions 1 and 2; the stop position is left out, like substring in Java
print(latency_ms.get("p99", 0))
print(a == b, a is b)
slow_ids = [t["id"] for t in tickets if t["ms"] > 1000]build a list of ids, one per ticket, keeping only tickets slower than 1000 ms: a filter and a map on one line
for i, t in enumerate(tickets, start=1):
yield row["ms"] / 1000
def chunk(text: str, size: int = 500, overlap: int = 50) -> list[str]:
def debug_call(*args, **kwargs):
print(f"{fn.__name__}: {ms:.1f} ms")
with deck_file.open() as f:open the file, run the indented block, then close the file no matter what, even if the block raises an error
deck = deck if deck is not None else []
Check your answers
head, *tail = valuesput the first item in head and the rest, as a new list, in tail. The star scoops up whatever is left, like ...rest in JavaScript
print(values[1:3])print the items at positions 1 and 2; the stop position is left out, like substring in Java
print(latency_ms.get("p99", 0))look up the key "p99" in the dict and print its value; if the key is missing, print 0 instead of raising an error
print(a == b, a is b)print two answers: whether a and b hold equal values, and whether they are the very same object in memory
slow_ids = [t["id"] for t in tickets if t["ms"] > 1000]build a list of ids, one per ticket, keeping only tickets slower than 1000 ms: a filter and a map on one line
for i, t in enumerate(tickets, start=1):loop over the tickets and get a counter alongside each one, starting the counter at 1 instead of 0
yield row["ms"] / 1000hand one value out to whoever asked for it, then pause the function right here until they ask for the next one
def chunk(text: str, size: int = 500, overlap: int = 50) -> list[str]:define a function taking a string and two optional numbers with defaults, returning a list of strings. The hints after the colons are for the type checker; Python ignores them at run time
def debug_call(*args, **kwargs):define a function that accepts any number of positional arguments, collected into a tuple, and any number of named arguments, collected into a dict
print(f"{fn.__name__}: {ms:.1f} ms")print a string with values filled in: the function's name, then the number ms rounded to one decimal place. The f before the quote turns on the curly-brace slots
with deck_file.open() as f:open the file, run the indented block, then close the file no matter what, even if the block raises an error
deck = deck if deck is not None else []keep deck as it is when the caller passed one; otherwise start a fresh empty list. The check uses is, because None is a single shared object

Do not worry if you got half of these. If you guessed that the star scoops up leftovers and that the square-bracket line is a filter plus a map, you are ahead of Marcus. He read this page's first ten lines as noise. The rest is spelling, and the next seven sections spell it out.

Step-by-step: what collections_tour.py does, in plain English
  1. Create one of each container: a list of four strings (order kept, duplicates allowed), a two-number tuple (fixed shape, cannot change), a dict mapping percentile names to milliseconds, and a set written with three strings that collapses to two, because sets drop duplicates.
  2. Append a fifth string to the list. Lists grow in place; nothing is copied.
  3. Print a slice, values[1:3]: the items at positions 1 and 2. The stop position is not included, the same rule as substring.
  4. Print values[-1]. A negative position counts from the end, so -1 is the last item.
  5. Look up a key that does not exist with .get("p99", 0). The second argument is the fallback, so the result is 0 and no error is raised.
  6. Unpack the tuple into two names, x and y, in one assignment. This is destructuring without the braces.
  7. Unpack the list with a star: head takes the first item and *tail collects everything else into a new list — a new object, in the sense drawn in Fig. A1.1b, not a window onto the old one.
  8. Loop over six values and print whether each counts as true. Empty things and zero are false; a non-empty string, even "0", is true.
  9. Build two separate lists with equal contents and print two comparisons. == asks whether the values match (True); is asks whether both names point at the same object (False).
collections_tour.pyruns offline
# stdlib only -- run with: python3 collections_tour.py
values = ["p95", "p99", "p50", "p95"]        # list: ordered, mutable, dupes ok
point = (3.5, 7.2)                           # tuple: fixed shape, immutable, hashable
latency_ms = {"p50": 210, "p95": 480}        # dict: key -> value
seen = {"p50", "p95", "p50"}                 # set: dupes collapse -- len(seen) == 2

values.append("p999")
print(values[1:3])               # ['p99', 'p50']   slice = [start, stop) like substring
print(values[-1])                # p999             negatives count from the end
print(latency_ms.get("p99", 0))  # 0                lookup with default -- no KeyError

x, y = point                     # unpacking: destructuring without the braces
head, *tail = values             # star scoops the rest, like JS ...rest
print(head, tail)                # p95 ['p99', 'p50', 'p95', 'p999']

# Truthiness: EMPTY things are falsy ("", [], {}, 0, None). Non-empty is truthy.
for candidate in ("", [], {}, 0, None, "0"):
    print(repr(candidate), "->", bool(candidate))
# '' -> False   [] -> False   {} -> False   0 -> False   None -> False   '0' -> True

# `is` compares IDENTITY (same object); == compares VALUE. Use `is` only for None.
a = [1, 2]; b = [1, 2]
print(a == b, a is b)            # True False -- equal values, different objects

Two habits to install now. First, None is Python's null, and the idiomatic check is x is None — identity, not equality — because None is a singleton and == can be overridden by classes. Second, slicing (xs[2:5], xs[-3:], xs[::2]) works on every sequence including strings; it always returns a new object and never throws on out-of-range bounds. You'll slice constantly when chunking documents in Module 08.

That second habit rests on the first, and the first is the most important picture on this page. A name in Python does not hold a value. It holds an arrow to an object, and two names can point at the same object. Everything below is drawn with the real output of collections_tour.py and of the prediction exercise two blocks down.

1 TWO OBJECTS THAT HOLD THE SAME THING a b [1, 2] object A [1, 2] object B a == b is True — the contents match a is b is False — two different objects the program prints: True False 2 ONE OBJECT, TWO NAMES nums alias [1, 2, 3, 4] one list object it held [1, 2, 3] until the append alias = nums copied the arrow, not the list. alias.append(4) changed that object, so nums prints [1, 2, 3, 4] too. 3 REBINDING MOVES ONE ARROW AND NOTHING ELSE nums alias [1, 2, 3, 4] the same object as marker 2 [9] a brand-new object alias = [9] does not touch the old list at all. nums still prints [1, 2, 3, 4]. assignment rebinds; it never copies.
Fig. A1.1b — Names and objects, the picture the rest of this page leans on: a name is an arrow, an object is what the arrow lands on, and only one of the three panels changes an object.
  1. Equal is not the same. Two lists were built, each holding 1 and 2. The contents match, so a == b is True. They are still two separate objects in memory, so a is b is False. This is exactly Java's equals against ==, with the words swapped round, and it is why the only thing you should test with is is None.
  2. One object, two names. alias = nums copies the arrow, not the list. Now alias.append(4) reaches through the arrow and changes the object itself. Nothing happened to the name nums, yet printing it shows four items. Java and JavaScript behave the same way with objects; the surprise in Python is that a plain list is one.
  3. Rebinding versus mutating. alias = [9] looks like a change to the shared list and is not. It builds a new object and points alias at it, leaving the old list exactly as it was. The rule that follows: name = something moves an arrow, while name.append(…), name[0] = … and name.sort() change the thing the arrow lands on.

Treat everything as an object.

Read a name as a pointer, not a box.

Expect assignment to rebind, never to copy.

Mutate through one name and every name sees it.

Ask is for identity and == for value.

Everything is an object: in Fig. A1.1b those are the boxes on the right, the things that actually hold [1, 2, 3, 4]. A name is a pointer: the boxes on the left, each with one arrow leaving it. Assignment rebinds: marker 3, where alias = [9] moves a single arrow and leaves the old list untouched. Mutate through one name and every name sees it: marker 2, where alias.append(4) changes the one object both names share. Ask is for identity: marker 1, where two objects with equal contents print True False.

1 SEVEN ITEMS, TWO SETS OF ADDRESSES index from the end 0 1 2 3 4 5 6 10 20 30 40 50 60 70 -7 -6 -5 -4 -3 -2 -1 2 xs[1:3] — THE START IS TAKEN, THE STOP IS NOT start 1: taken stop 3: left out xs[1:3] gives [20, 30] 3 minus 1 is 2, so two items. The 40 is where it stops. 3 FOUR MORE SLICES OF THE SAME SEVEN ITEMS xs[-2:] [60, 70] an empty stop means: keep going to the end xs[::2] [10, 30, 50, 70] the third number is the step: every second item xs[5:100] [60, 70] a stop past the end is clamped, never an error xs[::-1] [70, 60, 50, 40, 30, 20, 10] a step of -1 walks backwards: the reversed copy every one of these builds a NEW list. After all four, xs still holds its seven items.
Fig. A1.1c — Slicing the page's own list: the start position is taken, the stop position is not, and a slice always hands back a new list.
  1. Two addresses for every item. The row above the boxes counts from the left, starting at 0. The row below counts from the right, starting at -1. They name the same seven items, so xs[6] and xs[-1] both give 70. The negative row is what makes "the last three" a single expression, xs[-3:], with no len() arithmetic.
  2. Half-open, which is the part people get wrong. The two dashed lines are the cuts. The first cut is at position 1 and that item is taken; the second is at position 3 and that item is not. Subtracting gives the length straight away: 3 minus 1 is 2 items. Java's substring and JavaScript's slice use the same rule, so the arithmetic already lives in your fingers.
  3. The three forgiving behaviours. A missing stop means "to the end". A stop past the end is clamped instead of raising, so xs[5:100] is fine where substring would throw. A start already past the stop gives an empty list, again with no error. That forgiveness is why chunking a document in Module 08 needs no bounds checks.
Sharpen your pencil

Slicing is the idiom you will read most often in this course, so work it by hand once. Take xs = [10, 20, 30, 40, 50, 60, 70]. Positions run 0 to 6 from the left and -1 to -7 from the right. The two rows of positions, and the exact place where xs[1:3] starts and stops, are drawn in Fig. A1.1c directly above. Write the exact list each expression produces. Two rows are done for you.

xs[1:3][20, 30]: start at position 1, stop before position 3
xs[-2:]
xs[::2]
xs[5:100]
xs[3:1]
xs[::-1]
xs[-3:-1][50, 60]: negative positions still obey "stop is left out"
xs[1:3] is xs

Then answer: how many items does xs hold after all eight lines have run?

Check your answers
xs[1:3][20, 30]
xs[-2:][60, 70]. An empty stop means "to the end"
xs[::2][10, 30, 50, 70]. The third number is the step: every second item, starting at position 0
xs[5:100][60, 70]. A stop past the end is clamped, not an error. Java's substring would throw here
xs[3:1][]. Start is already past stop, so nothing is taken and, again, no error
xs[::-1][70, 60, 50, 40, 30, 20, 10]. A step of -1 walks backwards: the idiomatic reversed copy
xs[-3:-1][50, 60]
xs[1:3] is xsFalse. A slice is always a new list, never a view of the old one

And xs still holds seven items. Not one of the eight lines touched it. That is the property worth remembering: slicing reads, it never writes, and it never raises on out-of-range bounds. The one place it costs you is memory. Each slice copies its items' references into a new list, so slicing a million-item list inside a loop builds a million-item list every time.

🧠 Brain power

Predict the output before running it — all three prints:

predict_1.py
nums = [1, 2, 3]
alias = nums
alias.append(4)
first, *rest = nums
print(nums)
print(first, rest)
print(bool(""), bool([0]), bool("0"))
Reveal the answer

[1, 2, 3, 4] — assignment copies the reference, not the list, so alias and nums are the same object: that is marker 2 of Fig. A1.1b, drawn with these exact values (exactly like Java references). Then 1 [2, 3, 4] — unpacking sees the already-mutated list. Then False True True — the empty string is falsy, but [0] is a non-empty list (truthy despite containing a falsy value) and "0" is a non-empty string.

04 · Core PythonComprehensions, Iteration, and Generators

One of the five spellings in Fig. A1.0b was {t.id: t.text for t in tickets}, and it is the one Marcus stared at longest. He knows map. He knows filter. He had never seen them wearing one pair of brackets. This section takes that spelling apart, then takes apart the machinery under it: the iteration protocol, and the generator, which is how Module 06 streams tokens that do not exist yet. The habit being replaced is make an empty list, loop, append, return.

Here's the syntax that made Marcus bounce, cured in one paragraph.

A comprehension is filter + map read left to right: [x * 2 for x in xs if x > 0] means "a list of x * 2, for each x in xs, if x > 0".

Swap the brackets and you get the other collections: {k: v for …} builds a dict, {x for …} builds a set.

Course code prefers comprehensions over for-loop-and-append everywhere, for the same reason you prefer xs.map(f) over a mutating loop: the intent is declared, not assembled — and there's no accumulator variable to get wrong.

slow_ids = [t["id"] for t in tickets if t["ms"] > 1000] the line from iteration_tour.py, four clauses in one pair of brackets the comprehension, clause by clause the loop it replaces, line by line 1 [ … ] a list is what comes out 2 t["id"] the expression: one result per item kept 3 for t in tickets where the items come from 4 if t["ms"] > 1000 the filter: it runs first slow_ids = [] for t in tickets:     if t["ms"] > 1000:         slow_ids.append(t["id"]) Both sides print ['T-101'] — one id, because only that ticket took longer than 1000 ms. The crossing arrows are the whole surprise: Python writes the result first and the loop second. Java streams and SQL put the map last, which is why marker 2 feels out of place for one afternoon.
Fig. A1.1d — A comprehension is the four-line loop with the lines reordered: the result moves to the front, the loop and the filter stay in their original order behind it.
  1. The bracket says what you are building. Square brackets build a list, curly braces build a set, curly braces with a colon in the expression build a dict, and round brackets build a generator. On the loop side this is the slow_ids = [] line, the empty container you no longer have to create or name.
  2. The expression, and the crossing arrow. This is what goes into each slot of the result, and its arrow lands on the last line of the loop, the append. That crossing is the only real difference between the two sides. Read the expression first and you know what the line produces before you know where its data came from.
  3. The loop clause. Same words as the plain for line, minus the colon. The name t lives only inside the brackets and does not leak into the surrounding code, which is one fewer variable to accidentally reuse ten lines later.
  4. The filter. Written last, executed first: items that fail it never reach the expression. It takes no else, because an else would have to produce a value, and that belongs in the expression slot instead.
Anatomy of a comprehension — the one line to know by heart
slow_ids = [1t["id"]2 for t in tickets3 if t["ms"] > 10004]
  1. The opening bracket. It says what you are building: [ makes a list. Swap it for { and you build a set, or a dict when the expression has a colon. Swap it for ( and you build a generator, which computes nothing until asked. The common mistake is reading (x for x in xs) as a tuple. It is a generator, and it can be walked only once.
  2. The expression. What goes into each slot of the result: here, the ticket's id. It runs once per item that survives the filter. Engineers from Java streams and SQL expect the "map" part to come last. In Python it comes first, and reading it first tells you what the line produces.
  3. The loop. Where the items come from and what each one is called. t is a fresh name that exists only inside the brackets. It does not leak into the surrounding code, unlike the variable of a plain for loop. Two loops can be chained here, and they read left to right, outer loop first.
  4. The condition. The filter, and it runs before the expression: only items that pass reach the front of the line. It takes no else. If you need "this or that" per item, that is a conditional expression. It belongs in the expression slot: a if cond else b for t in tickets.
Step-by-step: what iteration_tour.py does, in plain English
  1. Define tickets: a list of three dicts, each holding an id, a priority, and a duration in milliseconds. This is the shape of nearly every record you will meet in the course.
  2. Build slow_ids with a list comprehension: for each ticket, keep it only if its duration is over 1000 ms, and take its id. Result: ['T-101'].
  3. Build a dict from id to duration with a dict comprehension, and a set of the priorities with a set comprehension. Same shape, different brackets. The set has two members because duplicates collapse.
  4. Loop with enumerate(tickets, start=1), which hands out a counter and the ticket together, so there is no index variable to maintain by hand.
  5. Pair two parallel lists with zip and turn the pairs into a dict. zip stops at the shorter list.
  6. Sort the tickets by duration with sorted(..., key=...). The key function says what to compare; the original list is left untouched. Take the first result's id: T-103.
  7. Define a generator, read_percentiles: a function with yield in it. Calling it runs none of its body; it returns an object that will run the body one step at a time, on demand.
  8. Call next() on it twice. Each call runs to the next yield, hands out one value in seconds, and pauses.
  9. Pass a fresh generator to sum(). Any loop or aggregate consumes a generator to the end; the total is 5.53 seconds.
iteration_tour.pyruns offline
# stdlib only -- run with: python3 iteration_tour.py
tickets = [
    {"id": "T-101", "priority": "high", "ms": 4200},
    {"id": "T-102", "priority": "low",  "ms": 950},
    {"id": "T-103", "priority": "high", "ms": 380},
]

# list comprehension: filter + map in one readable pass
slow_ids = [t["id"] for t in tickets if t["ms"] > 1000]
print(slow_ids)                          # ['T-101']

# dict and set comprehensions -- same shape, different brackets
by_id  = {t["id"]: t["ms"] for t in tickets}
levels = {t["priority"] for t in tickets}
print(by_id["T-103"], levels == {"high", "low"})   # 380 True

# enumerate and zip kill index bookkeeping -- you almost never write range(len(xs))
for i, t in enumerate(tickets, start=1):
    print(i, t["id"])                    # 1 T-101 / 2 T-102 / 3 T-103
names = ["p50", "p95"]; ms = [210, 480]
print(dict(zip(names, ms)))              # {'p50': 210, 'p95': 480}

# sorted() is non-destructive and key= takes ANY function -- your comparator
print(sorted(tickets, key=lambda t: t["ms"])[0]["id"])   # T-103

# A generator computes values ON DEMAND -- `yield` pauses, next() resumes
def read_percentiles(rows):
    for row in rows:
        yield row["ms"] / 1000           # seconds; nothing runs until asked

gen = read_percentiles(tickets)
print(next(gen), next(gen))              # 4.2 0.95
print(sum(read_percentiles(tickets)))    # 5.53 -- any loop/sum consumes a generator

The mechanism underneath all of this is the iteration protocol: anything with __iter__ can be looped, summed, unpacked, or comprehended — lists, dicts (keys), files (lines), and generators all speak it. A generator is a function with yield in it: calling it runs no code; each next() runs to the next yield, hands the value out, and freezes the function's locals mid-flight. It's C#'s yield return, JS's function*. Why care? Memory: a list of a billion rows must exist all at once; a generator holds one row at a time. Streaming LLM tokens in Module 06 is exactly this shape.

consumer (for / sum) generator (yield) next() — one value, please yield 4.2 — then pause locals + position frozen between calls list version: every row in memory before you touch one generator version: one row alive at a time — O(1) memory 1 2 3 4
Fig. A1.2 — Lazy evaluation: the consumer pulls, the generator computes one value and pauses; nothing is materialized that nobody asked for.
  1. The pull. Nothing happens until a consumer asks. A for loop, a sum, a list(…) call: all of them are just next() in a loop. This is the reverse of the arrangement you are used to, where the producer fills a collection and hands the whole thing over.
  2. The pause. The generator runs to its yield, hands out one value, and stops there with its local variables and its position in the loop still alive. The next next() resumes on the line after the yield. Nothing polls, nothing blocks; the function is simply frozen between calls.
  3. The list version. Eight boxes, all of them built before the consumer looks at the first one. With a million rows those boxes are a million objects, which is the arithmetic the pencil exercise above works out in bytes.
  4. The generator version. One box, reused. That is what "constant memory" means, and it is why a generator can stand in front of a 10 GB file or a model that is still producing its answer one token at a time.
Sharpen your pencil

Fig. A1.2 says the list version holds every row in memory and the generator holds one. Put numbers on that once and it will stay with you. Two lines, one million values each. On CPython 3.12 a list slot is an 8-byte pointer and a small integer object is 28 bytes. Fill in the blanks with arithmetic, not guesses.

doubled = [x * 2 for x in range(1_000_000)]builds the whole list before the assignment finishes
lazy = (x * 2 for x in range(1_000_000))builds a generator object; no value has been computed yet
Integers alive after line 1
Integers alive after line 2
Bytes for the list's slots: 8 × 1,000,000 =
Bytes for the integers: 28 × 1,000,000 =
Total for line 1, in MB (divide by 1,000,000)
Total for line 2, given sys.getsizeof(lazy) == 200
sum(lazy) run a second time returns
Check your answers
Integers alive after line 11,000,000. Every value exists before the next line runs
Integers alive after line 20. Nothing has run; the first value appears at the first next()
Bytes for the list's slots8,000,000. The measured figure is 8,448,728, because lists grow in steps and keep some spare room
Bytes for the integers28,000,000. Strictly 28 × 999,871: Python keeps one shared copy of every integer from -5 to 256, and the 129 values below 257 in this list reuse those
Total for line 1about 36 MB, before you have looked at a single value
Total for line 2200 bytes, plus one 28-byte integer at a time while it is being consumed. Roughly 180,000 times smaller
sum(lazy) run a second time0. The generator was used up by the first sum; a second pass yields nothing, and the sum of nothing is 0. No error, no warning

Two lessons hide in those numbers. First, the memory gap is not a rounding detail. It is 36 MB against 200 bytes for the same million values, and the ratio grows with the input. Streaming a file or a model's reply is generator territory for exactly this reason.

Second, the last row is the price. A generator can be walked once. Walk it again and you get silence, not an error. When you need to look twice, or need len(), or need position 500, you pay for the list.

Those two answers are worth one picture each, because they are the two facts that decide which one you reach for. The first is a size. The second is what happens on the second pass.

1 THE SAME MILLION VALUES, TWO SHAPES, MEASURED 36,448,728 bytes, all of it built before the next line runs list the list's slots: 8,448,728 B the 1,000,000 integers: 28,000,000 B generator 200 bytes — the sliver at the left edge of the same scale. Drawn at 3 pixels so it is visible; honestly it is four thousandths of one pixel. Add one 28-byte integer at a time while something is consuming it. 2 WALK IT ONCE AND IT IS GONE the generator's 1,000,000 values — none of them computed yet first sum(lazy): the head walks the whole tape and answers 999,999,000,000 second sum(lazy): the head is already at the end, so it sees nothing and answers 0 No error. No warning. A wrong number that looks like a right one.
Fig. A1.2b — The two facts that decide the choice, in measured numbers: 36,448,728 bytes against 200, and a second pass that silently answers 0.
  1. Why the list bar is in two pieces. The left piece is the list itself, 8,448,728 bytes of slots, which is the number sys.getsizeof reports. The right piece is the million integer objects those slots point at, 28 bytes each. The list does not contain the integers; it contains arrows to them, which is Fig. A1.1b again, a million times over.
  2. Why the generator bar is invisible. 200 bytes is the whole generator object: the frozen frame, the position, nothing else. Against 36 MB on the same scale it is four thousandths of a pixel, so it is drawn at 3 pixels as a courtesy. The ratio is about 180,000 to 1, and it grows with the input, because the generator's size does not.
  3. The price, drawn as a tape. The first sum pulls all million values and leaves the read head at the end. The second sum starts from where the head is, finds nothing, and returns the sum of nothing, which is 0. That is the failure the fireside chat in section 10 argues about, and the reason "walk it twice" means "make it a list".
🧠 Brain power

Predict the exact output, including the order of the first two lines:

predict_2.py
def countdown(n):
    print("starting")
    while n:
        yield n
        n -= 1

c = countdown(3)
print("created")
print(next(c))
print(next(c))
Reveal the answer

created, then starting, then 3, then 2. The surprise is the order: calling countdown(3) runs zero lines of its body — it just builds the generator object. The body (including that first print) only starts on the first next(), runs to yield n, and freezes. The second next() resumes after the yield, decrements, loops back, yields 2. If your mental model was "functions run when called", generators are the one place Python breaks it.

05 · Core PythonFunctions Properly — Up To and Including Decorators

Two of Marcus's five spellings are now dealt with. The line he bounced off was a function signature, and the libraries in this course are built almost entirely out of that one shape. The habit being replaced is method overloading and builder objects: Python gives you defaults and named arguments instead, which is why every LLM call in later modules reads like a block of configuration. The same two features are also what make the @ line on every test fixture, tool and route a plain ten-line function rather than framework magic.

Python functions have three calling-convention features you will meet on page one of every AI library.

The catch-alls look academic until you realise they are the fuel for the single most important pattern in this course's toolchain: the decorator.

Step-by-step: what functions_tour.py does, in plain English
  1. Bring in functools and time from the standard library. This script never calls them; they are the imports timed.py, the next file, builds on.
  2. Define chunk with two defaulted parameters, size=500 and overlap=50. The body computes a step and returns a list of slices of the text, one per step, using a comprehension over range.
  3. Call it on a 2000-character string with the defaults: a step of 450 gives 5 chunks. Call it again overriding only overlap by name: a step of 500 gives 4. Naming the argument is what lets you skip the one in the middle.
  4. Define debug_call(*args, **kwargs). The star collects any positional arguments into a tuple; the double star collects any named arguments into a dict. Call it with two numbers and one named value, and print both containers.
  5. Define shout as a one-line function, then put three callables in a list: shout, the built-in method str.strip, and a lambda that keeps the first ten characters. Functions are values, so a list can hold them.
  6. Loop over the list and apply each function to the text in turn, feeding each result into the next. Print the final string with repr so the quotes make the trimmed whitespace visible.
functions_tour.pyruns offline
# stdlib only -- run with: python3 functions_tour.py
import functools
import time

# Defaults + keyword args: callers name what they override.
def chunk(text: str, size: int = 500, overlap: int = 50) -> list[str]:
    step = size - overlap
    return [text[i:i + size] for i in range(0, len(text), step)]

print(len(chunk("x" * 2000)))               # 5
print(len(chunk("x" * 2000, overlap=0)))    # 4 -- override one arg by name

# *args / **kwargs: accept anything, forward everything.
def debug_call(*args, **kwargs):
    print("args:", args, "kwargs:", kwargs)

debug_call(1, 2, model="small")   # args: (1, 2) kwargs: {'model': 'small'}

# Functions are values: store them, pass them, return them.
def shout(s: str) -> str: return s.upper()
transforms = [shout, str.strip, lambda s: s[:10]]   # lambda: one-expression fn
text = "  hello, python  "
for fn in transforms:
    text = fn(text)
print(repr(text))                 # 'HELLO, PYT'

Now the payoff. A decorator is nothing but a function that takes a function and returns a wrapped version — the same higher-order move as Express middleware or a Java dynamic proxy. The @name line is pure sugar: @timed above def slow_sum means exactly slow_sum = timed(slow_sum). Here's a complete, useful one in ten lines:

Step-by-step: what timed.py does, in plain English
  1. Import functools for the wraps helper and time for a high-resolution clock.
  2. Define timed(fn): a function that takes a function. Everything it does is build and return a replacement.
  3. Inside it, define wrapper(*args, **kwargs). The catch-alls mean the wrapper accepts whatever the original accepted, without knowing its signature. @functools.wraps(fn) copies the original's name and docstring onto the wrapper, so tracebacks and help text still say slow_sum.
  4. The wrapper's body reads the clock, calls the original with every argument forwarded, reads the clock again, prints the difference in milliseconds, and returns the original's result unchanged.
  5. Return the wrapper. It keeps a reference to fn after timed has finished; that captured variable is what makes it a closure.
  6. Write @timed above def slow_sum. That single line means slow_sum = timed(slow_sum): the name now points at the wrapper.
  7. Call slow_sum(1_000_000). The wrapper runs, times the real sum of squares, prints the duration, and hands back the total.
timed.pyruns offline
# stdlib only -- run with: python3 timed.py
import functools
import time

def timed(fn):
    """Wrap fn so every call reports its duration."""
    @functools.wraps(fn)                  # keep fn's real name/docstring
    def wrapper(*args, **kwargs):         # accept anything...
        start = time.perf_counter()
        result = fn(*args, **kwargs)      # ...forward everything
        ms = (time.perf_counter() - start) * 1000
        print(f"{fn.__name__}: {ms:.1f} ms")
        return result
    return wrapper                        # wrapper CLOSES OVER fn -- a closure

@timed                                    # sugar for: slow_sum = timed(slow_sum)
def slow_sum(n: int) -> int:
    return sum(i * i for i in range(n))

print(slow_sum(1_000_000))
# slow_sum: 61.0 ms      (your number will vary)
# 333332833333500000
1 BEFORE THE @ LINE slow_sum the function you wrote: sum(i * i for i in range(n)) one object, one name pointing at it 2 @timed REBINDS THE NAME — THAT IS THE WHOLE TRICK @timed above def slow_sum means exactly: slow_sum = timed(slow_sum) slow_sum wrapper built and returned by timed(fn) closure: kept fn the function you wrote not modified, not copied the name moved to a new object; the original is still there, reachable only through the wrapper 3 WHAT ONE CALL NOW DOES: slow_sum(1_000_000) inside wrapper(*args, **kwargs) 1. read the clock 2. call the function you wrote, forwarding every argument it was given 3. read the clock again and print slow_sum: 61.0 ms 4. hand back 333332833333500000 — exactly what the original returned
Fig. A1.2c — A decorator is one rebinding: @timed makes the name slow_sum point at a wrapper that calls the original and times it.
  1. Before. One name, one function object. Nothing unusual, and this is still how every undecorated function on this page sits in memory.
  2. After. timed was handed the original and returned a different function. The @ line then pointed the old name at that new function. This is the same arrow-moving from Fig. A1.1b, marker 3, applied to a function instead of a list. The dashed arrow is the closure: the wrapper kept a private reference to the original, which is the only thing that can still reach it.
  3. The call, step by step. Callers still write slow_sum(1_000_000) and still get 333332833333500000 back. The four steps happen around that, not inside it. Because the wrapper takes *args, **kwargs, it can wrap a function of any signature without knowing one thing about it, and that is why the same ten lines work as a test fixture, an MCP tool and a web route.

Note the closure: wrapper keeps using fn long after timed returned — same lexical capture as a JS closure. This ten-line shape is not a curiosity; it's how half the course's tools present themselves. @pytest.fixture (Module 07), @mcp.tool (Module 10), and @app.post("/summarize") (Module 12, FastAPI) are all "function in, registered/wrapped function out". After today, you'll read them as plumbing, not magic. On lambda: it's for one-expression throwaways — key=lambda t: t["ms"] is its natural habitat. The moment logic needs two steps or a name, use def.

Questions you might be asking now

Fig. A1.2c says a call forwards every argument and a decorator is one rebinding. For an engineer arriving from Java or TypeScript, that raises two questions: what exactly does a function receive, and what runs when. Every answer below uses the same three tickets from iteration_tour.py.

The three tickets every answer below uses, exactly as iteration_tour.py builds them. For timing, decorator_timeline.py also makes queue = tickets * 100_000: 300,000 list slots that all point at these same three dict objects.
TicketprioritymsAs the program writes it
T-101high4,200{"id": "T-101", "priority": "high", "ms": 4200}
T-102low950{"id": "T-102", "priority": "low", "ms": 950}
T-103high380{"id": "T-103", "priority": "high", "ms": 380}
When I pass tickets into a function, does the function get a copy or the original? Is Python pass-by-reference or pass-by-value?

Neither, in the sense C++ gives those words. The parameter becomes a second name for the very same list, exactly like passing an object in Java or JavaScript. So queue.append(…) inside the function grew the caller's list from 3 tickets to 4, while queue = [] inside the function changed nothing outside it.

The Python documentation's own phrase is that arguments are passed by assignment. A call does exactly what an = does. Calling escalate(tickets) runs queue = tickets as the function starts. And the rebinding rule from Fig. A1.1b already told you what = does: it copies an arrow, never an object.

The script passing_and_rebinding.py makes the arrows visible. It gives every object it meets a short label: L1 for the first list, D1 for the first dict, I1 for the first int. Raw id() numbers are memory addresses that change on every run, so the labels are easier to read. Same label means same object.

Four small functions, one call each, as passing_and_rebinding.py printed them
CallThe function body doesInside the functionBack in the caller
escalate(tickets)queue.append(T104)queue → L1; queue is tickets is Truetickets → L1, now 4 tickets
clear(tickets)queue = []queue → L2, 0 ticketstickets → L1, still 4 tickets
bump(first_ms)ms += 100ms was I1 (4200), now I2 (4300)first_ms → I1, still 4200
mark_urgent(tickets[1])ticket["priority"] = "urgent"ticket → D1tickets[1] → D1, priority now 'urgent'

Read the four rows as two rules:

  • Change the object, and the caller sees it. Rows 1 and 4 reach through the arrow and change what it lands on. append, item assignment and sort() all work this way.
  • Rebind the name, and the caller does not. Rows 2 and 3 point the function's own name at a different object. The caller's name is a separate arrow, and nothing moved it.
1 escalate(tickets): THE PARAMETER IS A SECOND ARROW TO THE SAME LIST tickets the caller's name queue escalate's parameter L1: one list object [T-101, T-102, T-103, T-104] 3 tickets before the call, 4 after queue is tickets → True queue.append(T104) grew L1, so the caller now has 4 2 clear(tickets): queue = [] MOVES ONLY THE FUNCTION'S ARROW tickets the caller's name queue clear's parameter L1: [T-101, T-102, T-103, T-104] untouched: still 4 tickets L2: [] new and empty; dropped on return inside: queue → L2, 0 tickets after: tickets → L1, 4 tickets = moved one arrow: the local one 3 bump(first_ms): AN INT CANNOT CHANGE, SO ms += 100 BUILDS A NEW ONE first_ms the caller's name ms bump's parameter I1: 4200 I2: 4300 the caller still prints first_ms = 4200 dashed: where ms pointed before the += ms += 100 built I2 and moved ms to it Every call runs parameter = argument. A mutation reaches the caller; a rebinding never does.
Fig. A1.2i — What a function receives. The caller's name and the function's parameter are two arrows; the call makes the second one land where the first one does. Only a change to the object itself is visible on both sides. Labels L1, L2, I1 and I2 and all values from rerunning passing_and_rebinding.py.
  1. A second arrow, not a copy. Starting the call ran queue = tickets, so both names land on L1. That is why queue is tickets printed True inside the function. queue.append(T104) changed the object itself, so the caller sees 4 tickets without ever touching its own name.
  2. Rebinding stays inside. queue = [] built a new list, L2, and moved only the function's arrow. The caller's arrow never moved, so tickets still lands on L1 with its 4 tickets. When clear returns, nothing points at L2 any more, and Python frees it.
  3. An int looks copied, and is not. An int object cannot be changed, so ms += 100 has nothing to grow. It builds I2, holding 4300, and moves the function's arrow to it; the dashed line is where that arrow started. The caller's first_ms still lands on I1, holding 4200.

Now the words themselves. People use "by reference" for two different behaviours, and only one of them exists in Python:

What the caller sees in each language, for the two kinds of change a function can make
Passing…The function mutates it (append)The function assigns to its parameter (= [])
An object in JavaCaller sees the changeCaller sees nothing
An object or array in JavaScript or TypeScriptCaller sees the changeCaller sees nothing
Anything at all in PythonCaller sees the changeCaller sees nothing
A variable in C# with ref, or in C++ with &Caller sees the changeCaller sees it too: this is true pass-by-reference

So Python behaves exactly as Java does for objects, with one simplification. In Python everything is an object, so there is no second rule for primitives. An int is simply an object nobody can change, which is why row 3 of the first table looks like Java copying an int. Nothing was copied there; a new int was built.

The honest limit cuts both ways. There is no way to write a Python function that rebinds the caller's variable, the way C# ref can. A function that makes a new list must return it, and the caller writes tickets = clear(tickets). And nothing stops a function from mutating what you pass in.

If you need the original kept safe, pass a copy: escalate(list(tickets)). Remember Gotcha 3 in section 10, though. list(…) copies only the outer list, so mark_urgent on that copy would still change the three shared dicts.

A call runs parameter = argument. The function gets a second arrow to your object: mutations are shared, rebinding is private, and nothing is ever copied.

Inside a function, queue += [t] changed my list, but queue = queue + [t] did not. Aren't those the same line?

No. On a list, += means "extend this very object", so every name that points at it sees the new ticket. queue + [t] builds a brand-new list, and the = points only the function's name at it. Measured: after += the caller still had list L3, now with 4 tickets; after = … + the caller still had list L4 with 3.

In Java or TypeScript, x += y is shorthand for x = x + y, full stop. Python lets each type decide what += means. A list defines its own in-place version; an int, a string and a tuple do not. Here is what Python does with queue += [T104], in order:

  1. Ask the object first. Python looks for an in-place add on the object queue points at. A list has one, a method called __iadd__.
  2. Extend in place. The list's __iadd__ appends the new ticket to L3 itself, then returns L3.
  3. Assign the result back. Python runs queue = whatever step B returned. That is L3 again, so the arrow lands where it already was.
  4. The fallback for types that cannot change. An int, a str or a tuple has no in-place add. Python uses the plain + instead, which builds a new object, and step C moves the arrow to it.
The two functions side by side, called on fresh copies of the three tickets, as passing_and_rebinding.py printed them
add_in_place: queue += [T104]add_by_copy: queue = queue + [T104]
Caller's list before the callL3, 3 tickets, slots D2 D3 D4L4, 3 tickets, slots D5 D6 D7
queue after the lineL3, the same object, 4 ticketsL5, a new object, 4 tickets
What the new ticket went intoA fourth slot on L3L5's slots: D5 D6 D7 D8, the three old dicts plus T-104
Caller's list after the callL3, 4 ticketsL4, still 3 tickets
Pointers copied14: the 3 already there, plus the new one
1 queue += [T104]: EXTEND THIS LIST tickets caller queue function L3 T-101 T-102 T-103 T-104 one list, grown by one slot L3 before, L3 after: tickets now has 4 pointers copied: 1 2 queue = queue + [T104]: BUILD A NEW LIST tickets caller queue function L4 T-101 T-102 T-103 T-104 L5 tickets → L4, still 3; queue → L5, 4 tickets pointers copied: 3 old + 1 new = 4 3 THE PRICE OF COPYING: A QUEUE BUILT ONE TICKET AT A TIME, MEASURED 10,000 tickets = + : 88.5 ms += : 0.92 ms 20,000 tickets = + : 397.7 ms += : 1.87 ms 40,000 tickets = + : 1,555.1 ms += : 3.83 ms each doubling of the queue: = + took 4.5 and then 3.9 times longer, while += took about 2 times longer
Fig. A1.2j — The two lines drawn side by side on fresh copies of the three tickets, and what each one costs when it runs thousands of times. Labels, pointer counts and timings from rerunning passing_and_rebinding.py; the timings are CPU time on one machine and will differ on yours.
  1. One object, one more slot. += asked L3 to extend itself, so the new ticket landed in a fourth slot of the list both names already shared. Then the name was assigned back to the same L3. One pointer was copied, and the caller's tickets has 4 tickets.
  2. A new object, and only one name moved. queue + [T104] built L5 and filled it with arrows to the three existing dicts plus T-104. The dicts were not copied, only the arrows to them. Then = moved the function's name to L5, and the caller's L4 kept its 3 tickets.
  3. The copying adds up. In a loop, queue = queue + [t] copies every pointer already in the list, every time. For 20,000 tickets that is 0 + 1 + 2 + … + 19,999 = 199,990,000 pointer copies. That took 397.7 ms of CPU time here, against 1.87 ms for +=. Double the tickets and the copying roughly quadruples, while += only doubles.
The same alias = value, then value += extra, on four types, as passing_and_rebinding.py printed it
TypeLinealias is value afterwardsaliasvalue
list["T-101"] += ["T-102"]True['T-101', 'T-102']['T-101', 'T-102']
int4200 += 100False42004300
str"T-10" += "1"False'T-10''T-101'
tuple("T-101",) += ("T-102",)False('T-101',)('T-101', 'T-102')

One well-known oddity proves that steps B and C really are two separate steps. Put a list inside a tuple, then use += on it: pair = (["T-101"], 4200), then pair[0] += ["T-102"].

The line raised TypeError: 'tuple' object does not support item assignment. Yet printing pair afterwards showed (['T-101', 'T-102'], 4200). Step B extended the list, which is allowed. Step C then tried to store the result back into slot 0 of the tuple, which a tuple forbids. The official Python FAQ lists this exact case.

The difference also has a price, drawn in marker 3 of Fig. A1.2j. queue = queue + [t] copies every pointer the list already holds.

Build a queue of n tickets one at a time that way, and the copies add up. The total is 0 + 1 + 2 + … + (n − 1), which is n × (n − 1) ÷ 2. For 20,000 tickets that is 199,990,000 copies.

Measured in CPU time on one machine, that loop took 397.7 ms, against 1.87 ms with +=: about 212 times longer. Your numbers will differ; the shape will not. Doubling the queue multiplied the slow loop's time by about 4 and the fast loop's by about 2.

For one call on three tickets, neither line costs anything you could measure. So choose by meaning, not speed. Use += or append when every holder of the list should see the new ticket. Use + when you want a new list and the caller's list left alone.

On a list, += changes the object every name shares, while x = x + y builds a new object and moves one name. On an int, a str or a tuple, += can only do the second.

Walk one call through @timed, line by line. What runs when the file loads, and what runs when I call the function?

Two separate moments. When Python reaches @timed and the def under it, it calls timed once, builds the wrapper and points the name at it; nothing is timed yet. Every later call runs only the wrapper, which calls your original function once, in the middle. Counted over two calls: timed ran 1 time, the wrapper 2 times, the original 2 times.

Fig. A1.2c drew what one call does. The missing piece is when each line runs. In Java, an annotation is metadata that some framework reads later. A Python decorator is ordinary code, and it runs at a moment you can print.

The script decorator_timeline.py is timed.py from the page with a numbered log line at each moment. It decorates total_ms(rows), which adds up the ms field of every ticket it is given. Then it calls it twice: once on the 300,000-slot queue, once on the three tickets.

What decorator_timeline.py printed, in order, and what is happening at each line
StepPrinted by the scriptWhat is happening
1file loads: the def timed line runsdef creates a function object named timed. None of its body runs.
2file loads: reached @timed and the def under itPython builds the plain total_ms function object first.
3timed() runs, handed the function object 'total_ms'The @ line calls timed(total_ms). This is the only time timed ever runs.
4timed() returns the wrapper; the @ line points the name at ittotal_ms = timed(total_ms) is now complete.
5name total_ms -> a function whose code is 'wrapper', __name__ still says 'total_ms'functools.wraps copied the name across, not the code.
6 to 9call 1: total_ms(queue) … total_ms: 8.8 ms … call 1 returned 553,000,000The wrapper ran around the original: clock, call, clock, print, return.
10 to 13call 2: total_ms(tickets) … total_ms: 0.0 ms … call 2 returned 5,530The same wrapper again. timed did not run again.

Now zoom into call 1, the steps inside the wrapper, one line at a time:

  1. The name leads to the wrapper. total_ms(queue) looks up total_ms and finds the wrapper. *args collects (queue,) and **kwargs collects an empty dict.
  2. Read the clock. start = time.perf_counter().
  3. Call the original. fn(*args, **kwargs) unpacks back into fn(queue). fn is your original total_ms, kept by the closure. It adds 300,000 ms values: 5,530 × 100,000 = 553,000,000.
  4. Read the clock again, and print. 8.782 ms had passed, printed rounded as total_ms: 8.8 ms. That is wall-clock time on one machine; yours will differ.
  5. Return the original's result unchanged. The caller receives 553,000,000 and cannot tell a wrapper was involved.
1 WHEN THE FILE LOADS: THESE RUN ONCE, BEFORE ANY CALL def timed(fn): makes timed; body not run @timed / def total_ms builds your plain function timed(total_ms) builds and returns wrapper total_ms → wrapper the name is rebound log steps 1 to 5; __name__ still says 'total_ms' only because functools.wraps copied it 2 CALL 1: total_ms(queue), 300,000 SLOTS: ONLY THE WRAPPER'S LINES RUN inside wrapper(*args, **kwargs) start = perf_counter() read the clock fn(queue) your body: 300,000 values read the clock again prints total_ms: 8.8 ms return result 553,000,000, unchanged 3 CALL 2: total_ms(tickets), 3 TICKETS: THE SAME WRAPPER, AND timed DOES NOT RUN AGAIN inside wrapper(*args, **kwargs) start = perf_counter() read the clock fn(tickets) your body: 3 values read the clock again prints total_ms: 0.0 ms return result 5,530, unchanged counted by the script: timed ran 1 time · wrapper ran 2 times · your original body ran 2 times 0.0 ms is honest: three tickets took 0.0053 ms, and timed.py rounds to one decimal place
Fig. A1.2k — The two moments of a decorator. The top row runs once, while the file loads; the two lower rows are the wrapper running around your function, once per call. Log order, counts and timings from rerunning decorator_timeline.py; the milliseconds are wall-clock on one machine.
  1. Once, at definition. Steps 1 to 5 of the log. The @ line waits for the def under it to build your function, calls timed with it, then points the name at whatever timed returned. Nothing is timed here. Had this file been imported rather than run, all of this would happen during the import.
  2. Call 1, around your code. The caller wrote total_ms(queue) and reached the wrapper. The wrapper's four lines ran in order. Only the green box is your original function, reached through the closure. It returned 553,000,000, and the wrapper passed that on untouched.
  3. Call 2, the same wrapper. Three tickets instead of 300,000, so the clock read 0.0053 ms and printed 0.0 ms. The shape is identical: the wrapper ran again, the original ran again, and timed did not. The counter line at the bottom confirms it.

Two things follow from the timeline, and both matter in later modules:

  • Decorators run when the file is imported. An import runs a file top to bottom, as section 08 showed, so every @ line in it runs its decorator right then. That is how @mcp.tool in Module 10 and @app.post in Module 12 register a function before anyone calls it. It is also why a slow decorator makes an import slow.
  • Stacked decorators apply from the bottom up. @a above @b above def f means f = a(b(f)). b wraps your function first, and a wraps what b returned.

The honest limit is in step 5. functools.wraps copies the name, the docstring and a few other attributes onto the wrapper. It also stores your original as total_ms.__wrapped__. It does not make them the same function: the code behind the name is still the wrapper's, which is what step 5 printed.

@timed runs once, when the def runs, and rebinds the name. Every call after that runs the wrapper, which calls your original in the middle.

What if I put @timed on a generator function? Does it time the work?

No. Calling a generator function runs none of its body, so the wrapper times only the creation of a generator object, and prints slow_ids: 0.0 ms. The real work, checking 300,000 slots for slow tickets, happens later, when something pulls the values. Measured: the decorator saw 0.0019 ms; the pull took 9.4 ms, and nothing timed it.

This is the countdown prediction from section 04 meeting the decorator from Fig. A1.2k. Calling countdown(3) printed nothing, because a function with yield in it hands back a generator object and runs no body lines. The wrapper's clock sits around exactly that call.

The script decorator_timeline.py puts @timed on slow_ids(rows), a generator that walks the rows and yields the id of every ticket slower than 1,000 ms. Then it runs gen = slow_ids(queue) and, on a later line, list(gen). In order:

  1. The call reaches the wrapper. Log steps 3 and 4. The wrapper reads the clock and calls the original with queue.
  2. The original returns at once. Calling a generator function builds a generator object: the rows, plus a paused position at the top of the body. Not one ticket is checked.
  3. The wrapper stops the clock and prints. Log step 5: slow_ids: 0.0 ms. The raw reading was 0.0019 ms, the cost of building one small object.
  4. The caller now holds the generator. Log step 6. The wrapper has returned; its clock is gone for good.
  5. list(gen) pulls every value. Log steps 7 to 9. Only now does the body run: 300,000 slots checked, 100,000 ids yielded, 9.4 ms, with no clock running.
The same @timed on the two kinds of function, from decorator_timeline.py
total_ms, an ordinary functionslow_ids, a generator function
What fn(*args, **kwargs) returnsThe answer, 553,000,000A generator object, with no work done
When the body runsInside the wrapper, between the two clock readingsLater, wherever the values are pulled
What the clock measuredThe work: 8.782 msBuilding one object: 0.0019 ms
What it printedtotal_ms: 8.8 msslow_ids: 0.0 ms

To time the work, the clock has to run while the values are pulled. The script's fix is timed_gen, a wrapper that is itself a generator. Its body is yield from fn(*args, **kwargs) inside a try, with the clock read before it and again in the finally. yield from hands on each value the original yields, one at a time, as the consumer asks.

timed against timed_gen, line by line
Jobtimedtimed_gen
Start the clockBefore calling fnOn the first next(), when the wrapper's own body starts
Run the workresult = fn(*args, **kwargs)yield from fn(*args, **kwargs): pass on each value as it is pulled
Stop the clockRight after fn returnsIn finally:, after the last value, or when the consumer stops early
Printed for the 300,000-slot queue0.0 ms10.2 ms
1 @timed: THE CLOCK STOPS BEFORE THE WORK STARTS @timed list(gen) clock: 0.0019 ms, printed slow_ids: 0.0 ms 300,000 slots checked in 9.4 ms, with no clock running 2 @timed_gen, A FAST CONSUMER: THE CLOCK SPANS THE PULL @timed_gen clock: printed 10.2 ms list(slow_ids2(queue)): the same 100,000 ids 3 @timed_gen, A SLOWER CONSUMER: THE CLOCK COUNTS THE CONSUMER TOO @timed_gen 10.2 ms in row 2 clock: printed 48.6 ms for the same 100,000 ids; the loop did a little extra work per id 0 10 20 30 40 50 milliseconds after the pull begins, one shared axis, wall-clock on one machine
Fig. A1.2l — Where the clock sits. Row 1 is plain @timed on a generator: its clock window closes before the work begins. Rows 2 and 3 are timed_gen, whose clock spans the pull, including whatever the consumer does between values. Values from rerunning decorator_timeline.py.
  1. The clock stops before the work starts. The red sliver is the wrapper's whole clock window: 0.0019 ms, the time it takes to build a generator object. The grey bar is the real work, done afterwards by list(gen) while no clock was running. timed.py reports what it saw, and it saw almost nothing.
  2. A clock around the pull. timed_gen's wrapper is a generator too, so its clock starts at the first next() and stops in its finally after the last value. The bracket now spans the pull: 10.2 ms, close to the 9.4 ms of row 1's untimed bar. This is the number you wanted.
  3. The consumer is inside the window. The same generator yielded the same 100,000 ids. The loop pulling them did a little extra work per id, and the clock read 48.6 ms. The clock measures from the first value to the last, and the consumer's work in between counts.

Marker 3 is the honest limit of the fix. timed_gen measures wall time from the first value to the last, not the generator's own work. Use it to answer "how long did this stream take", not "how slow is this generator".

The same trap waits in Module 01 and Module 06. Calling an async def function also returns at once, with a coroutine object instead of a generator. decorator_timeline.py put @timed on one that awaits a 50 ms sleep. The decorator printed fetch_ticket: 0.0 ms, and awaiting the coroutine took 50.7 ms. Timing async code needs an async def wrapper that awaits the original.

A decorator times the call, and calling a generator or an async function does no work yet. Time the consumption instead: wrap with yield from, or await inside an async wrapper.

🧠 Brain power

The * in a signature makes everything after it keyword-only. Predict what happens:

predict_3.py
def greet(name, *, loud=False):
    return name.upper() if loud else name

print(greet("Ada", True))
Reveal the answer

TypeError: greet() takes 1 positional argument but 2 were given. The bare * is a fence: loud can only be passed as greet("Ada", loud=True). Library authors use this deliberately so call sites stay readable — you'll see keyword-only params throughout the OpenAI and Anthropic SDKs, which is why their calls look like create(model=…, max_tokens=…, messages=…).

06 · Core PythonClasses, Dataclasses, and Why the Course Mostly Uses Pydantic

Marcus writes classes all day, so this part transfers almost intact. What does not transfer is how many of them he needs, and how much of each he has to type. Two surprises first, both cosmetic, then the thing course code actually uses: a decorator that writes the constructor, the printer and the equality check from a list of typed fields. The habit being replaced is the deep hierarchy with hand-written getters and an equals you hope somebody kept in step with the fields.

Python classes hold two surprises for Java/TS refugees, both cosmetic. First, __init__ is the constructor (the double underscores — "dunders" — mark methods Python itself calls). Second, self is just this made explicit: it's the first parameter of every method, filled in automatically when you call obj.method(). That's genuinely the whole trick — methods are ordinary functions stored on a class.

Step-by-step: what classes_tour.py does, in plain English
  1. Import dataclass and field from the standard library.
  2. Define Ticket the manual way. __init__ is the constructor; self is the instance being built, passed in automatically. Each assignment to self.something creates an attribute.
  3. Build a ticket and print its two attributes. Then compare two tickets built from the same values: the result is False, because a plain class compares by identity unless you write __eq__ yourself.
  4. Define Card with @dataclass. The class body is a list of fields with type hints; the decorator writes __init__, __repr__ and __eq__ from that list.
  5. Give streak a default of 0 and tags a default of field(default_factory=list). The factory builds a fresh list per instance; a bare [] would be shared by every card, which is the trap in section 10.
  6. Add a @property named mastered. It is a method that reads like an attribute: c.mastered, with no parentheses, runs it and returns True once the streak reaches 3.
  7. Build a card and print it: the generated __repr__ shows every field. Compare it with an identical card: True, because the generated __eq__ compares field by field.
  8. Set the streak to 3 and read mastered: True.
classes_tour.pyruns offline
# stdlib only -- run with: python3 classes_tour.py
from dataclasses import dataclass, field

# The manual way -- fine, but boilerplate you'll stop writing today.
class Ticket:
    def __init__(self, id: str, priority: str = "low") -> None:
        self.id = id
        self.priority = priority

t = Ticket("T-101", "high")
print(t.id, t.priority)                  # T-101 high
print(Ticket("T-1") == Ticket("T-1"))    # False -- default == is identity!

# @dataclass generates __init__, __repr__, __eq__ from the field list.
@dataclass
class Card:
    front: str
    back: str
    streak: int = 0
    tags: list[str] = field(default_factory=list)  # why not []? See "Watch it break"

    @property
    def mastered(self) -> bool:          # computed attribute -- read without ()
        return self.streak >= 3

c = Card("What does `is` compare?", "Object identity")
print(c)   # Card(front='What does `is` compare?', back='Object identity', streak=0, tags=[])
print(c == Card("What does `is` compare?", "Object identity"))   # True -- by value now
c.streak = 3
print(c.mastered)                        # True
1 WHAT YOU WRITE 2 WHAT @dataclass WRITES FOR YOU @dataclass class Card:     front: str     back: str     streak: int = 0     tags: list[str] = field(...) __init__(self, front, back, streak=0, tags=...) the constructor, in field order __repr__(self) prints every field by name when you print the card __eq__(self, other) compares field by field, in order 3 THE DIFFERENCE IT MAKES, IN THE SCRIPT'S OWN OUTPUT plain class, no decorator Ticket("T-1") == Ticket("T-1") False — Python fell back to "same object?" the same two values, as a dataclass Card(front, back) == Card(front, back) True — compared field by field tags uses field(default_factory=list), so every card gets its own empty list, never one shared list. mastered is a @property: set c.streak = 3 and c.mastered reads True, with no brackets and no stored field.
Fig. A1.2d — @dataclass reads the typed field list and writes three methods, which is why the same two cards now compare True instead of False.
  1. The field list is the input. Four lines, each a name and a type, two of them with defaults. That list is the only thing the decorator reads. Add a field and all three generated methods change with it, which is the part a hand-written equals always eventually forgets.
  2. The three methods are the output. A constructor in field order, a printer that names every field, and an equality test that compares them one by one. They are ordinary methods on an ordinary class; nothing dynamic happens at call time.
  3. Why the two results differ. A plain class has no idea what "equal" should mean, so Python falls back to "is it the very same object", which is Fig. A1.1b marker 1 all over again, and two separately built tickets are never the same object. The dataclass supplies the missing definition. The default_factory line on the last field exists for the trap in section 10: a bare [] there would be one list shared by every card ever made.

The idiom this course lives by: data first, inheritance rarely. Modern Python (and modern AI code in particular) models the domain as typed records — dataclasses — plus plain functions that transform them. Deep class hierarchies are as rare in 2026 Python as they are in modern TypeScript. You'll see exactly one upgrade beyond @dataclass in this course: Pydantic models (Module 01), which look nearly identical but validate at runtime — feed one malformed JSON and it raises a precise error instead of storing garbage. Dataclasses trust their caller; Pydantic checks the border. Course rule of thumb: dataclass for internal state, Pydantic wherever data crosses a boundary — API responses, LLM structured outputs, config files.

🧠 Brain power

Predict both prints:

predict_4.py
from dataclasses import dataclass

@dataclass
class Point:
    x: int
    y: int

p, q = Point(1, 2), Point(1, 2)
print(p == q)
print(p is q)
Reveal the answer

True then False. @dataclass generated an __eq__ that compares field-by-field, so == is value equality — but they're still two distinct objects, so is (identity) is False. A plain class without @dataclass would print False False: default == falls back to identity, exactly like Java's == on objects.

07 · Core PythonErrors & Files — EAFP, raise, and What with Actually Does

Every tour script so far has assumed that nothing goes wrong. Marcus's instinct is to check first: does the file exist, is this string a number, is the key present. Python's instinct is the opposite, and it is not laziness. A pre-check races, because the file can vanish between the check and the open. The habit being replaced is look-before-you-leap, and what replaces it is try the real thing and catch the one failure you can name. The section ends on with, which gives him the same guarantee try-with-resources already gives him today.

Python's error culture differs from Java's in philosophy, not machinery. The community idiom is EAFP — "easier to ask forgiveness than permission": try the happy path and catch the specific failure, rather than pre-checking every condition (LBYL, "look before you leap").

EAFP wins in Python because exceptions are cheap, and because pre-checks race: the file you os.path.exists()-checked can vanish before you open it.

The full statement has four clauses — try / except / else (runs only if nothing was raised) / finally (runs no matter what):

Step-by-step: what errors_tour.py does, in plain English
  1. Import json and Path. Then write a small JSON file, deck.json, so the script has something real to load.
  2. Define load_deck(path). The try body holds only the two lines that can fail: reading the file and parsing the text.
  3. First except: if the file is missing, return an empty deck. A missing file is a normal state here, not a bug.
  4. Second except: if the text is not valid JSON, raise a ValueError that names the file. from err attaches the original parse error, so the traceback shows both.
  5. else runs only when nothing was raised: return the parsed deck. Keeping the return out of the try body means a bug in it cannot be mistaken for a file error.
  6. finally runs on every path, success or failure, and prints a line. This is where cleanup goes.
  7. Call the function on the real file and print the first card's front; then call it on a missing file and see the empty deck. Both print "load attempted" first.
  8. Open the file with with. Entering the block calls the file's __enter__; leaving it, even by an exception, calls __exit__, which closes the file. Print the length of its contents.
  9. Delete the demo file with unlink().
errors_tour.pyruns offline
# stdlib only -- run with: python3 errors_tour.py
import json
from pathlib import Path

deck_file = Path("deck.json")
deck_file.write_text(json.dumps({"cards": [{"front": "EAFP?", "back": "Ask forgiveness"}]}))

def load_deck(path: Path) -> dict:
    try:
        raw = path.read_text()             # may raise FileNotFoundError
        deck = json.loads(raw)             # may raise json.JSONDecodeError
    except FileNotFoundError:
        return {"cards": []}               # a missing deck is just an empty deck
    except json.JSONDecodeError as err:
        # Re-raise as OUR error; `from err` chains the original traceback.
        raise ValueError(f"{path} is corrupt: {err}") from err
    else:
        return deck                        # only reached if nothing raised
    finally:
        print("load attempted")            # cleanup line: runs on every path

print(load_deck(deck_file)["cards"][0]["front"])
# load attempted
# EAFP?
print(load_deck(Path("missing.json")))
# load attempted
# {'cards': []}

# `with` = a try/finally you can't forget. Entering calls __enter__,
# leaving calls __exit__ (close/release/rollback) -- even if the body raises.
with deck_file.open() as f:
    print(len(f.read()))                   # 58
deck_file.unlink()                         # tidy up the demo file
1 FOUR CLAUSES · ONE PATH PER CALL 2 run A: the file is there 3 run B: no such file try: read the file, parse the JSON except FileNotFoundError: return an empty deck except JSONDecodeError: raise ValueError ... from err else: return the parsed deck finally: print "load attempted" nothing raised, so both handlers are skipped read_text raised FileNotFoundError, so the first handler answers and else is skipped run A prints, in this order load attempted EAFP? run B prints, in this order load attempted {'cards': []}
Fig. A1.2e — Two calls to the same function, two routes through the same four clauses; only finally is on both routes, which is why "load attempted" is printed twice.
  1. The column is the statement. Read it top to bottom: the risky lines, then one handler per failure you can name, then the clause for "it all worked", then the clause that runs whatever happened. Only the two risky lines are inside try. That is deliberate: if the return statement were in there, a bug in it would be caught by your file handler and reported as a file problem.
  2. Run A, the left rail. The file exists and the JSON parses, so neither handler is entered, else returns the deck, and finally prints. Notice the order in the output: "load attempted" appears before the card's text, because finally runs on the way out of the function, before the caller's print gets the value.
  3. Run B, the right rail. read_text raises, so the rest of the try body is abandoned mid-flight, the matching handler returns an empty deck, and else never runs. finally still prints. Swap the file for corrupt text and the second handler runs instead, raising a ValueError that names the file while from err keeps the original parse error in the traceback.

Three rules of raising well: catch the narrowest exception you can name (bare except: hides bugs and eats Ctrl-C); raise types that tell the caller what to do (ValueError for bad input, custom exceptions for domain failures); and chain with raise … from err so the original cause survives in the traceback. And for files: it's pathlib.Path everywhere in this course — path.read_text(), path.write_text(), path / "subdir" / "file.json" — the object-oriented API that replaced the os.path string-mangling era. A context manager (the thing with drives) is any object with __enter__/__exit__; it's C#'s using, Java's try-with-resources. Module 06 streams LLM responses inside a with block for exactly this guarantee: the connection closes even when your code throws mid-stream.

🧠 Brain power

Which lines print, in what order?

predict_5.py
try:
    x = int("42")
except ValueError:
    print("bad")
else:
    print("good", x)
finally:
    print("done")
Reveal the answer

good 42 then done. int("42") succeeds, so except is skipped and else runs — else exists so you can keep the try body down to the one risky line, with the follow-on code outside the blast radius. finally runs on success, failure, even on return. Change "42" to "forty-two" and you'd get bad then done.

08 · Core PythonModules, __main__, and a Ten-Line Preview of uv

Six hours was the promise, and about here Marcus wants to know where the code lives and how the dependencies get installed. A Python file is a module, and importing it runs it, which is the fact behind the odd-looking line at the bottom of every script on this page. Then the part his package.json instincts already cover: a project file, a lock file and a per-project interpreter. The habit being replaced is one machine-wide Python with a pile of pip install in it.

A Python module is just a file — importing it executes it top to bottom, once, and caches the result in sys.modules (so a second import is a cheap dict lookup, like Node's require cache). A package is a directory of modules. from metrics import p95 is your named import; import metrics then metrics.p95(…) is your namespace import. Because importing runs the file, every script you'll see in this course guards its entry point:

Step-by-step: what metrics.py does, in plain English
  1. Define p95: sort a copy of the list and return the value 95% of the way along it. This is the reusable part, and the reason another file would import this one.
  2. Check __name__. Python sets this variable to the string "__main__" only in the file it was asked to run; in an imported file it holds the module's own name, "metrics".
  3. If the check passes, run a self-test and print the result. Under import metrics the check fails and this block is skipped, so importing the module has no side effects.
metrics.pyruns offline
# A module IS a file. Run directly:  python3 metrics.py  -> self-test runs.
# Import from elsewhere: `import metrics` -> self-test does NOT run.
def p95(xs: list[float]) -> float:
    return sorted(xs)[int(len(xs) * 0.95)]

if __name__ == "__main__":
    # __name__ is "__main__" only when THIS file is the program being run;
    # under import, it's the module's own name ("metrics").
    print("self-test:", p95(list(range(100))) == 95)   # self-test: True

Environments: Python's answer to node_modules is the virtual environment — a per-project interpreter + packages directory. The historical pain (venv activation dances, requirements.txt drift) is over; the 2026 tool is uv, and Module 01 sets it up properly. Ten-line preview so it isn't a surprise:

You are not expected to run or memorise the commands below yet. They are here so the shape of a project looks familiar later. Module 01 sets one up step by step, with a lockfile, a test runner and a type checker.

uv_preview.shpreview — full setup in Module 01
# uv (astral.sh/uv): package manager, venv, and Python versions in ONE tool.
# Your package.json instincts transfer directly (as of Aug 2026):
curl -LsSf https://astral.sh/uv/install.sh | sh   # install once per machine

uv init demo && cd demo      # pyproject.toml  ==  package.json
uv add httpx "pydantic>=2.7,<3"   # npm install --save (exact pins -> uv.lock)
uv add --dev mypy pytest          # devDependencies
uv run python main.py             # npx: runs inside the project venv, no "activate"
uv run mypy .                     # dev tools resolve from the same lockfile
uv sync                           # npm ci: reproduce the env bit-for-bit anywhere
1 IMPORTING A FILE RUNS IT — ONCE import metrics is "metrics" already in sys.modules? no yes run metrics.py top to bottom, then store it hand back the stored module — no code runs so a top-level print in metrics.py appears once, however many files import it. 2 THE SAME FILE, TWO ROLES python3 metrics.py __name__ holds "__main__" the guarded block runs: self-test: True import metrics __name__ holds "metrics" the guarded block is skipped: no side effects 3 WHERE THE PACKAGES COME FROM uv add uv sync uv run pyproject.toml uv.lock .venv/ uv run python main.py what you asked for pydantic>=2.7,<3 the exact versions that satisfied it one interpreter and exactly those packages no activate step same result on every machine
Fig. A1.2f — Two mechanisms that trip people up on day one: an import runs the file exactly once, and the packages a run can see come from the project's own lock file and folder.
  1. The cache is the whole story. The first import runs the file and stores the resulting module object under its name. Every later import is a dictionary lookup that returns that same object. So module-level code is an initialiser that runs once, and two modules that import each other get the half-built version, which is the one real hazard here.
  2. One file, two roles. Python sets __name__ to "__main__" in the file you asked it to run, and to the module's own name everywhere else. Guarding the self-test with that check is what lets the same file be both a program and a library. Without the guard, importing metrics would run its self-test as a side effect of the import.
  3. The packaging chain. pyproject.toml is the range you asked for and uv.lock is the exact set that satisfied it, down to hashes. uv sync builds .venv/ from the lock file, so two machines get byte-identical dependencies. uv run then uses that folder without any activation step, which is the part that removes the classic "it works on my machine" failure. Module 01 sets all four up properly.
🧠 Brain power

Predict: metrics.py starts with a top-level print("loading metrics"). Another file runs import metrics twice in a row. How many times does it print — and what would python3 metrics.py print?

Reveal the answer

Once. The first import executes the file (printing the line); the second finds metrics already in sys.modules and reuses it — module top-level code is effectively a memoized initializer. Running python3 metrics.py directly prints the line too, and runs anything under if __name__ == "__main__":, because now the file is the program, not an import.

The stack, and why

Before the type-hint section, here is every tool this page leans on, and what you would pick instead.

The stack, and why

The one question that decides it: do you need this project to run the same way on someone else’s machine next year? (As of November 2026.)

What the Python primer uses, what else you could use, and when to switch
LayerWe useAlternativesWhy this oneSwitch when
Language and runtimeCPython 3.12, standard library only (every *_tour.py file)Newer CPython 3.x, PyPy, TypeScript, GoThe default interpreter that every AI library targets first. Weakness: slow for hand-written loops over millions of items.PyPy only for long pure-Python loops with no C libraries; Go or Java for a service where one request must cost well under 1 ms of CPU.
Project and environmentsuv (previewed in §08, set up in Module 01)pip with venv, Poetry, condaOne tool for the interpreter, the virtual environment and the lock file, and very fast. Weakness: newer than pip, so some old tutorials do not match it.conda when you need non-Python system libraries such as CUDA builds; plain pip when a locked-down server only allows it.
Type checkingType hints checked by mypy (typing_tour.py)pyright, ty, no checkerMature and the one most tutorials show. Weakness: slower than newer checkers on big code bases.pyright when your team lives in VS Code; ty (still in beta as of late 2026) once your code base takes more than about 30 seconds to check.
RecordsDataclasses (classes_tour.py), with Pydantic at the edgesNamedTuple, TypedDict, attrsDataclasses are in the standard library and cost nothing to import. Weakness: they do not check types at run time.Pydantic the moment the data comes from outside your program (an API body, an LLM reply, a file).
Number crunchingNumPy (list_vs_numpy.py, section 11)Plain lists, the array module, PolarsOne block of raw numbers in C, so 1,000,000 values add in milliseconds. Weakness: an extra install, and arrays have one fixed type.Plain lists below about 1,000 numbers; a data-frame library such as Polars once you have named columns (see Python for data).
TestsAn assert self-test under __main__ (metrics.py)pytest, unittestNothing to install, and it shows the idea. Weakness: it stops at the first failure and gives no report.pytest when you have more than a handful of tests or need fixtures; it is what the later modules use.

Start with the standard library and one tool (uv), and add a library only when a named problem, such as validation or speed, appears.

09 · Core PythonType Hints That Matter

Marcus is a TypeScript engineer, so this is the section where he asks where his compiler went. The honest answer is that there is no compiler. There is a separate program you choose to run, and it reads hints that the interpreter itself throws away. The habit being replaced is trusting the build to stop a bad call before it ships. What replaces it is hints on the borders plus a checker in the pipeline, which is also what will catch the mistakes an LLM makes in Module 15 when it writes code inside his repository.

Before the objection below, look at the split, because everything in this section follows from it. One signature, two readers, and only one of them cares.

1 ONE SIGNATURE, TWO READERS def slow_ids(     rows: list[TicketRow],     cutoff_ms: int = 1000, ) -> list[str]: the hints are these three pieces of text mypy or pyright a separate program you run reads every annotation CPython, at run time the program itself stores them, never checks them 2 WHAT THE CHECKER SAYS ABOUT ONE BAD CALL slow_ids(rows, cutoff_ms="1000") error: Argument "cutoff_ms" to "slow_ids" has incompatible type "str"; expected "int" [arg-type] 3 WHAT THE RUNTIME DOES WITH THE SAME CALL It runs it. The hints sit in __annotations__ as text and are never consulted. avg(["1", "2"]) starts fine and then dies inside sum() with a TypeError. A function hinted -> int that returns "42" runs happily and misleads every reader until the checker runs.
Fig. A1.2g — The division of labour: the checker reads the annotations before the program runs, and the runtime keeps them as text and ignores them completely.
  1. Two readers, one source. The annotations are ordinary parts of the source. The checker on the left is a program you install and run, like a linter. The interpreter on the right stores them on the function and never consults them. Nothing in Python enforces a hint at run time, and no hint makes your code slower.
  2. What you get for the effort. One bad call, one exact message, before anything runs: the argument name, the type you passed, the type expected, and a code you can look up. Run it in your editor and you get the same message as a red squiggle; run it in the pipeline and a wrong call cannot merge.
  3. What you do not get. The same wrong call, if you never run the checker, just runs. It may work by accident, or it may fail three functions later inside somebody else's code, which is the TypeError in sum(). This is also why a wrong annotation is worse than none: it passes at run time and lies to every reader. Pydantic, in Module 01, is the piece that actually checks at run time, at the borders where the data is untrusted.

"Eight sections in and half these functions have no types on them. Where are my types? In Go the compiler would have thrown this whole page back at me."

— a Go engineer, and every Java engineer, right about now

They are optional, and that is a design choice you will have to make peace with. The split is marker 1 of Fig. A1.2g, directly above: the same signature is read by two programs, and only the one on the left cares. That left-hand program is mypy or pyright, and marker 2 is the message it gives you for one wrong argument. Marker 3 is what the interpreter does with the very same call, which is run it. A script with no hints runs; a script with wrong hints also runs. The checker is a linter you choose to run, locally and in CI.

What you get in exchange is a gradual dial. The tour scripts above hint every function signature and leave the local variables alone, because the checker infers those. Course code is written that way on purpose: hints on the borders, where a wrong type does damage, and nothing in the middle. In Module 15 those border hints are what let mypy catch mistakes in code an LLM wrote for you.

The honest downside: nothing stops a wrong annotation from shipping. A function hinted -> int that returns a string passes at run time and misleads every reader until the checker runs. Some libraries ship poor or missing type information, so Any leaks in and the checker goes quiet exactly where you wanted it loud. Pydantic, in Module 01, closes that gap at the boundaries that matter.

Python's type hints are TypeScript's deal with different fine print: annotations are ignored at runtime (no compile step rejects a bad call) and enforced by an external checker — mypy or pyright — run like a linter, locally and in CI. The modern syntax is compact: built-in generics (list[str], dict[str, int] — no List import since 3.9) and pipe unions (str | None — the honest "maybe missing" type, your string | null).

Step-by-step: what typing_tour.py does, in plain English
  1. Import TypedDict. It describes the shape of a dict for the type checker: which keys exist and what type each value has. At run time a TicketRow is an ordinary dict.
  2. Define slow_ids: it takes a list of rows and a cutoff with a default, and returns a list of strings. The body is the same filter-and-map comprehension from section 04.
  3. Define find: it returns either a row or None, and the hint TicketRow | None says so out loud. The body collects matches and returns the first, or None if there were none.
  4. Build two rows and call both functions. The prints show a list with one id, then None for an id that does not exist.
  5. The last line is a comment showing what mypy would reject: passing the string "1000" where an int is expected. Python itself would run that call and fail later, inside the comparison.
typing_tour.pyruns offline
# stdlib only -- run: python3 typing_tour.py   check: uv run mypy typing_tour.py
from typing import TypedDict

class TicketRow(TypedDict):        # the SHAPE of a dict, for the checker's eyes
    id: str
    ms: int

def slow_ids(rows: list[TicketRow], cutoff_ms: int = 1000) -> list[str]:
    return [r["id"] for r in rows if r["ms"] > cutoff_ms]

def find(rows: list[TicketRow], id: str) -> TicketRow | None:   # may be absent
    matches = [r for r in rows if r["id"] == id]
    return matches[0] if matches else None

rows: list[TicketRow] = [{"id": "T-1", "ms": 1400}, {"id": "T-2", "ms": 90}]
print(slow_ids(rows))          # ['T-1']
print(find(rows, "T-9"))       # None
# mypy would reject: slow_ids(rows, cutoff_ms="1000")   [arg-type]
Decision table: the three ways to model a record — choose one deliberately
OptionChoose whenAvoid whenRuntime cost
TypedDictData is already a dict (JSON in flight) and you only want checker-time shape safetyYou need methods, defaults, or validationZero — it IS a dict
@dataclassInternal state you construct yourself; want __init__/__eq__/repr freeData arrives from outside and might be malformedTiny — plain attributes
Pydantic modelData crosses a boundary: API payloads, LLM structured outputs, configHot inner loops that never see untrusted dataValidation on construct — worth it at borders

Why this section earns its place in an AI course: typed Python is the substrate of the whole 2026 LLM stack. Pydantic models are type hints turned into runtime validators; FastAPI and FastMCP generate schemas from your annotations; and when you point an LLM coding agent at your codebase in Module 15, type hints are precisely what lets it — and mypy — catch the agent's mistakes before runtime. Untyped Python plus an eager code-generating LLM is how subtle bugs ship; typed Python turns a whole class of them into red squiggles.

🧠 Brain power

Given def avg(xs: list[float]) -> float: return sum(xs) / len(xs) — which of these does mypy flag, and what happens at runtime for each? (a) avg([1, 2, 3]) (b) avg(["1", "2"])

Reveal the answer

mypy flags only (b) — list[str] isn't list[float]. It accepts (a) because int is compatible where float is expected. At runtime, (a) returns 2.0; (b) crashes with TypeError inside sum() — the hints did nothing to stop it, because hints are never enforced at runtime. That division of labor — checker before runtime, nothing during — is the whole model.

There are no dumb questions

Indentation as syntax — seriously? What happens when tabs and spaces mix?
Python 3 refuses to run a file that mixes them ambiguously, so the horror stories are mostly Python-2 folklore. In practice you'll never think about it: every editor inserts 4 spaces, and formatters (ruff format, Module 01) normalize everything. You already indent your braces-language code exactly like this — Python just deleted the redundant characters.
Isn't Python too slow for AI work?
Your Python is the orchestration layer; the heavy math runs in C, C++, and CUDA underneath numpy and PyTorch. LLM applications specifically spend their lives waiting on the network, where Python's speed is irrelevant and its async story (Module 01) is what matters. When you do hit CPU-bound Python, the fixes are vectorization or processes — covered exactly there.
Why do I have to write self everywhere?
Because methods are ordinary functions stored on a class, and Python makes the receiver an explicit parameter instead of an implicit this. t.close() is sugar for Ticket.close(t). One rule ("first param is the instance") replaces a chapter of this-binding rules — ask a JS developer about bind() sometime.
Which Python version does the course assume?
3.12, pinned via uv in Module 01 (as of Aug 2026). Everything on this page needs only 3.10+ — list[str] generics and X | None unions are the newest syntax used. If python3 --version says 3.10 or later, every block here runs as-is.
Do I need to memorize the standard library?
No. The ~20 constructs on this page cover about 95% of the Python you'll read in this course. The stdlib is a lookup problem — and you have an LLM for lookup problems. Fluency in the constructs is the part lookup can't give you.

10 · Watch it breakThe Five Classic Gotchas, Demonstrated

Nine sections of how Python works. This one is the bill. Five things compile, run, and quietly do the wrong thing, and four of the five come straight from the picture in section 03: a name is an arrow to a shared object. They are also the five questions a screening interview asks in its first fifteen minutes, which is the other reason Marcus needs them by name. The habit being replaced is the quiet assumption that something, somewhere, made a copy.

Failure mode

Every one of these compiles, runs, and silently does the wrong thing — Python's five classic traps for engineers arriving from other languages. Each traces back to one of two facts you've already met: names are references to shared objects, and some things are evaluated once, earlier than you think. Run the block, watch it lie to you, and you're inoculated — these five are also the top Python screening questions in interviews.

BE the interpreter

Your turn to play the machine. Here is a three-line function, then three calls and four prints. Run it in your head using two rules only. A default value is created once, when def runs. A name is a pointer to an object. With a pencil, write the four lines the prints produce.

be_the_interpreter.py
def tag(item, tags=[]):
    tags.append(item)
    return tags
  1. a = tag("urgent")
  2. b = tag("billing")
  3. c = tag("refund", [])
  4. print(a); print(b); print(c); print(a is b)

Most engineers write ['urgent'] for the first line. Commit to your four lines before you open the answer.

Check your answer

The real output is ['urgent', 'billing'], then ['urgent', 'billing'] again, then ['refund'], then True. The first line is the surprise. a was returned before "billing" existed, yet it shows both items.

Here is why. The empty list was built once, when def ran, and stored on the function object. Call 1 appended to that list and returned it, so a points at it. Call 2 appended to the same list and returned it, so b points at it too. a did not change; the object it points at did. That is what a is b being True means.

Call 3 passed its own fresh list, so the default was never touched and c is independent. The lesson is the one the chant in section 03 compresses. Names point at objects, and returning a list hands out a pointer, not a copy. The fix, a None sentinel and a fresh list inside the body, is Gotcha 1 in the file below.

Here is the same three calls drawn on one timeline, with the contents of the default list written under each call. Check your four lines against it before reading on.

1 ONE LIST, MADE ONCE, WHEN def RAN def tag(item, tags=[]) tag("urgent") tag("billing") tag("refund", []) [] the default list ['urgent'] the same list ['urgent', 'billing'] still the same list ['refund'] the caller's own list the default is stored on the function object, so it survives between calls and keeps whatever the last call appended 2 WHERE a, b AND c POINT WHEN ALL THREE CALLS ARE DONE ['urgent', 'billing'] one object, returned twice ['refund'] a separate object a b c a is b is True, so both print ['urgent', 'billing'] c is untouched by either of them, because call 3 supplied its own list
Fig. A1.2h — The mutable default across three calls: one list is created when def runs, and every call that omits the argument appends to that same list.
  1. The moment the list is made. It is made once, while the def line executes, which is before any call happens. It is not made fresh per call. That single fact is the whole gotcha, and it is why the growing contents under calls 1 and 2 are the same object twice, not two objects.
  2. Why a changed after it was returned. a never changed. Call 1 returned a pointer to the list, and call 2 appended to that same list. Printing a afterwards shows two items because the object behind the arrow grew. This is Fig. A1.1b marker 2 with a function wrapped around it.
  3. Why call 3 escaped. It passed its own list, so the default was never touched. That is also the shape of the fix: default to None, and build a fresh list inside the body when nothing was passed. The dataclass version of the same fix is field(default_factory=list), which is exactly why Card.tags is written that way in Fig. A1.2d.

Build it in chunks

We build gotchas.py in three chunks, two or three gotchas at a time. Each chunk runs on its own; the whole file comes at the end. The files are in code/a1-python-primer/ladder/.

  1. Chunk 1 — the mutable default argument, and its fix

    This is the gotcha that bites first and most often, and it needs no imports, so it is the smallest runnable program in the file.

    Step-by-step: what chunk 1 does, in plain English
    1. add_card has a default deck=[]. That empty list is made once, when def runs.
    2. Calling it twice without a deck appends to the same list both times, so the second call shows both cards.
    3. add_card_fixed uses None as a marker and builds a fresh list inside each call.
    gotchas.py — chunk 1runs offline
    # GOTCHA 1 -- the mutable default argument (THE classic)
    def add_card(front, deck=[]):          # [] is evaluated ONCE, at def time
        deck.append(front)
        return deck
    
    print(add_card("a"))    # ['a']
    print(add_card("b"))    # ['a', 'b']   <- surprise: same list as the last call!
    
    def add_card_fixed(front, deck=None):  # the idiom: None sentinel...
        deck = deck if deck is not None else []   # ...fresh list per call
        deck.append(front)
        return deck
    
    print(add_card_fixed("b"))             # ['b']

    Default argument — evaluated once at def time, not on every call.

    Run python3 chunk1_default.py. You should see these three lines: ['a'], ['a', 'b'], ['b'].

  2. Chunk 2 — late-binding closures and shallow copies

    Both gotchas are the same kind of surprise as chunk 1: Python keeps a pointer, not a snapshot. Closures point at a variable; a shallow copy points at the same inner lists.

    Step-by-step: what chunk 2 does, in plain English
    1. Build three lambdas in a loop. Each looks up i only when called, by which time the loop has ended at 2, so all three return 2.
    2. Give the lambda a default i=i and each freezes the value it saw.
    3. Make a 2 by 2 grid, copy it with list(grid), change one inner cell through the copy and see the original change too.
    4. copy.deepcopy copies all the way down, so changing the deep copy leaves the original alone.
    gotchas.py — chunk 2runs offline
    import copy      # at the top of the file
    
    # GOTCHA 2 -- late-binding closures: `i` is looked up at CALL time
    fns = [lambda: i for i in range(3)]
    print([f() for f in fns])              # [2, 2, 2]  -- not [0, 1, 2]!
    fns = [lambda i=i: i for i in range(3)]   # default arg captures i's value NOW
    print([f() for f in fns])              # [0, 1, 2]
    
    # GOTCHA 3 -- copying copies the box, not the contents
    grid = [[0, 0], [0, 0]]
    shallow = list(grid)                   # new outer list, SAME inner lists
    shallow[0][0] = 9
    print(grid[0])                         # [9, 0]  <- mutated through the "copy"
    deep = copy.deepcopy(grid)
    deep[1][1] = 7
    print(grid[1])                         # [0, 0]  -- deep copy is independent

    copy.deepcopy — copies a nested structure completely; a lambda default argument as a snapshot trick.

    Run python3 chunk2_closure_copy.py. You should see the three lines from chunk 1, then the four new ones (the last four values below): ['a'], ['a', 'b'], ['b'], [2, 2, 2], [0, 1, 2], [9, 0], [0, 0].

  3. Chunk 3 — mutating a list mid-loop, and floats (this is the whole program)

    The last two gotchas are independent of the first three, so they come last. With them the file is complete.

    Step-by-step: what chunk 3 does, in plain English
    1. Loop over [2, 2, 3] and remove each even number. Removing shifts the next item into the slot the loop already passed, so the second 2 is skipped and the list ends as [2, 3].
    2. A list comprehension builds a new list instead and gets the right answer, [3].
    3. Add 0.1 and 0.2: the sum is 0.30000000000000004, and == against 0.3 is False.
    4. math.isclose compares with a small tolerance and returns True.
    gotchas.py — chunk 3runs offline
    import math      # at the top of the file
    
    # GOTCHA 4 -- never mutate a list you're iterating
    nums = [2, 2, 3]
    for n in nums:
        if n % 2 == 0:
            nums.remove(n)                 # shifts elements under the iterator
    print(nums)                            # [2, 3]  <- it MISSED the second 2
    print([n for n in [2, 2, 3] if n % 2]) # [3]     -- build a new list instead
    
    # GOTCHA 5 -- floats are binary fractions (every language; Python shows it)
    print(0.1 + 0.2)                       # 0.30000000000000004
    print(0.1 + 0.2 == 0.3)                # False
    print(math.isclose(0.1 + 0.2, 0.3))    # True -- compare with tolerance, always

    math.isclose — compare floats with tolerance; list comprehension with a condition as the safe way to filter.

    Run python3 chunk3_loop_float.py. The last five values are the new ones; the whole output is: ['a'], ['a', 'b'], ['b'], [2, 2, 2], [0, 1, 2], [9, 0], [0, 0], [2, 3], [3], 0.30000000000000004, False, True.

The whole program

Chunk 1 is gotcha 1, chunk 2 is gotchas 2 and 3, chunk 3 is gotchas 4 and 5. Each chunk starts with a # ── chunk n ── comment. The two imports sit at the top of the file, where Python expects them: copy is used from chunk 2 and math from chunk 3.

Step-by-step: what gotchas.py does, in plain English
  1. Import copy for deep copies and math for tolerant float comparison.
  2. Gotcha 1. Define add_card with deck=[]. That list is created once, when def runs. Two calls that omit deck both append to it, so the second call prints ['a', 'b'].
  3. The fix: default to None, then inside the body build a fresh list when nothing was passed. Each call now starts empty.
  4. Gotcha 2. Build three lambdas in a comprehension, each returning i. They do not capture the value of i; they look it up when called, and by then the loop has finished at 2. All three return 2.
  5. The fix: lambda i=i: i. A default argument is evaluated at definition time, so each lambda freezes the i it saw.
  6. Gotcha 3. list(grid) makes a new outer list whose slots point at the same inner lists. Changing an inner value through the copy changes the original. copy.deepcopy copies all the way down, so the deep copy is independent.
  7. Gotcha 4. Remove items from a list while looping over it. Removing the first 2 shifts the second 2 into the slot the loop has already passed, so it is skipped. Build a new list with a comprehension instead.
  8. Gotcha 5. Add 0.1 and 0.2: binary floats cannot hold either exactly, so the sum is not 0.3 and == says False. Compare with math.isclose, which allows a tiny tolerance.
gotchas.pyruns offline
# stdlib only -- run with: python3 gotchas.py
# ── chunk 1: the mutable default ──
import copy
import math

# GOTCHA 1 -- the mutable default argument (THE classic)
def add_card(front, deck=[]):          # [] is evaluated ONCE, at def time
    deck.append(front)
    return deck

print(add_card("a"))    # ['a']
print(add_card("b"))    # ['a', 'b']   <- surprise: same list as the last call!

def add_card_fixed(front, deck=None):  # the idiom: None sentinel...
    deck = deck if deck is not None else []   # ...fresh list per call
    deck.append(front)
    return deck

print(add_card_fixed("b"))             # ['b']

# ── chunk 2: closures and copies ──
# GOTCHA 2 -- late-binding closures: `i` is looked up at CALL time
fns = [lambda: i for i in range(3)]
print([f() for f in fns])              # [2, 2, 2]  -- not [0, 1, 2]!
fns = [lambda i=i: i for i in range(3)]   # default arg captures i's value NOW
print([f() for f in fns])              # [0, 1, 2]

# GOTCHA 3 -- copying copies the box, not the contents
grid = [[0, 0], [0, 0]]
shallow = list(grid)                   # new outer list, SAME inner lists
shallow[0][0] = 9
print(grid[0])                         # [9, 0]  <- mutated through the "copy"
deep = copy.deepcopy(grid)
deep[1][1] = 7
print(grid[1])                         # [0, 0]  -- deep copy is independent

# ── chunk 3: mutating a loop, and floats ──
# GOTCHA 4 -- never mutate a list you're iterating
nums = [2, 2, 3]
for n in nums:
    if n % 2 == 0:
        nums.remove(n)                 # shifts elements under the iterator
print(nums)                            # [2, 3]  <- it MISSED the second 2
print([n for n in [2, 2, 3] if n % 2]) # [3]     -- build a new list instead

# GOTCHA 5 -- floats are binary fractions (every language; Python shows it)
print(0.1 + 0.2)                       # 0.30000000000000004
print(0.1 + 0.2 == 0.3)                # False
print(math.isclose(0.1 + 0.2, 0.3))    # True -- compare with tolerance, always

Gotcha 1 deserves the diagram, because the fix (None sentinel, and field(default_factory=list) back in the dataclass section) only sticks once you see the mechanism: default values live on the function object, created once when def executes — so every call that omits the argument shares one list.

function object add_card __defaults__ = ( • ) created once, at def time the ONE list ['a', 'b'] call 1: add_card('a') deck call 2: add_card('b') deck every call that omits `deck` binds to the same object — appends accumulate across calls 1 2 3
Fig. A1.3 — The mutable-default mechanism: the default list is created once and stored on the function object; every defaulted call mutates that same shared list.
  1. The function object holds the defaults. A function in Python is an object, and its default values are stored on it in an attribute called __defaults__. The dot in that tuple is a pointer, not a value. Every default you write lives there from the moment def runs until the program ends.
  2. The one list. Because the pointer never changes, there is exactly one list for the life of the function, and it is the accented box. Appending to it in one call is visible in the next, which is why the second call prints ['a', 'b']. An immutable default such as 0 or "p95" is harmless here for exactly this reason: nothing can change it.
  3. Both calls bind to it. Each call that omits the argument binds its local name deck to that same object, on the left and on the right of the picture. A caller who passes a list of their own binds to theirs instead and never touches this one, which is the third station in Fig. A1.2h.

Before the two of them argue, look at what each one actually costs and refuses. Every claim in the chat below points at a numbered row in this picture, and all five numbers came off this page's own code.

THE LIST THE GENERATOR 1 a million values 36,448,728 bytes, before you read one 200 bytes, plus one 28-byte integer 2 the second pass the same answer, every time 0 — nothing left, and no warning 3 len, item 500, slicing all three, and instantly TypeError — the fix is list(gen) 4 values not produced yet cannot hold what has not arrived one at a time, constant memory 5 saving it anywhere JSON, pickle, a database row not data — a promise to make data 6 walk it once, or it is large, or it has not arrived yet → use the generator look twice, index it, sort it, save it → use the list
Fig. A1.3b — The two roles with the numbers attached: five rows where one of them wins, and the rule that falls out of them.
  1. Memory. The measured sizes from the pencil exercise in Fig. A1.2b: 36,448,728 bytes against 200. This is the row the generator wins outright, and the gap grows with the input.
  2. The second pass. A list gives the same answer a thousand times. A generator gives it once and then answers 0 for ever, with no error to tell you. This is the row that costs people an afternoon.
  3. Random access. len(), xs[500] and slicing are list-only. On a generator all three raise TypeError, and the cure is always list(gen), which pays the memory bill in row 1 on purpose.
  4. Values that do not exist yet. A model producing tokens, a 10 GB log being read, a socket delivering rows. A list has to wait for all of them and then hold all of them. A generator hands each one on as it appears.
  5. Saving. Anything you want to write to disk, put in JSON or send over a wire has to be data. A generator is not data; it is a recipe with a bookmark in it. That is why every result that leaves a program ends up in a list, a dict or a file.
  6. The rule. Two lines, and they decide it every time. Walk once, large, or still arriving: generator. Look twice, index, sort, save: list. Nothing else in the argument below changes this answer.
Fireside chat

Tonight's talk: The List and The Generator argue over the question, "Who's more important?"

The List
The Generator

Let's start with what the reader can see. Marker 3. Print me and you get my contents. Ask my length and you get a number. Ask for item 500 and you get item 500. All three of those are a TypeError on you. Print you and you get <generator object <genexpr> at 0x7f...>. That is not a data structure, that is an IOU.

a list can be printed, measured and indexed straight away. A generator supports none of that, because it has not computed anything yet.

An IOU that never asks for 36 megabytes up front. Marker 1: the same million values are 36,448,728 bytes through you and 200 bytes through me, measured, not guessed. And marker 4 is the row you cannot argue with. When a model streams its answer one token at a time, the tokens do not exist yet. You cannot hold what has not arrived. I can.

the memory gap in row 1 is measured on this page, and row 4 is the case where a list is not slower but impossible: the values have not been produced yet.

And when the reader wants to look twice? Marker 2. The first sum answered 999,999,000,000 and the second answered 0. No error, no warning, just a wrong number sitting in a report. I can be walked a thousand times and give the same answer every time. You are single-use, and you fail silently, which is the worst way to fail.

row 2: a generator can be walked once. The second walk finds nothing and quietly returns the sum of nothing, which is zero.

Silently? Read gotchas.py again. The reader removed items from you while looping over you and you skipped an element without a sound. Two lines earlier, list(grid) copied your outer box and shared your insides, so a write through the copy changed the original. I have no insides to share. Nobody can mutate me mid-loop, because I am the loop.

lists have silent failures of their own. Removing items while iterating skips some, and a shallow copy still shares the inner lists.

Those are misuse, not design. Marker 3 again: slicing, len(), item 500. Every one of those is a TypeError on you, and the fix is always the same, list(gen) — which pays marker 1's bill on purpose. The moment a program needs to do anything but walk forward once, it turns you into me.

row 3 is the reason generators keep being converted back into lists, and that conversion is exactly the memory cost of row 1.

Because turning me into you is cheap and the reverse is not. Marker 4, in practice: a pipeline of three generators reads a 10 GB log in constant memory and starts printing results before the first megabyte is done. Rebuild that with lists and you wait for the whole file to load, then hold three copies of it. Being convertible is my strength, not my weakness.

generators chain without materialising anything in between, so a three-stage pipeline still holds one row at a time.

Your body does not even run when you are called. The reader saw it in the countdown prediction: countdown(3) printed nothing, and "starting" only appeared on the first next(). An exception in your body is raised where you are consumed, which can be three functions away from where you were written. Debugging that is a treasure hunt.

calling a generator function runs none of its body, so errors inside it surface later, at the place that consumes it.

Laziness is the feature. The sum(i * i for i in range(n)) inside timed.py never built a list of a million squares, and nobody had to think about it. That expression is me, in round brackets. The reader has been using me all page without noticing, which is the highest compliment a data structure can get.

a generator expression inside a call needs no extra brackets, so most readers never notice they are using one.

And every one of those results was stored in me afterwards. Marker 5. JSON serialises me. The cards in deck.json live in me. You cannot be written to disk, pickled, or sent over a wire, because you are not data. You are a promise to compute data.

row 5: anything that leaves the program has to be data, so results end up in a list, a dict or a file.

A promise that scales. Marker 6, the band across the bottom, is the rule the reader should take home, and we both agreed to it. Walk once, or the input is large or still arriving: use me. Look twice, index, sort, or save: use you. We'll revisit who's more important when the reader hits a file that does not fit in memory.

the bottom band is the decision rule, and it is the one line worth memorising from this whole argument.

Or a bug that does not fit in a traceback. Your move.

neither wins. The picture above is the answer: pick the row that matches what your code actually needs to do.

11 · Under the hoodHow CPython Actually Runs Your Code

Marcus can now read the course's Python. The last thing he needs is why it behaves the way it does when it gets slow, because that is the question his team will ask him in review. Three facts carry most of it: the source is compiled to bytecode, one lock lets one thread run that bytecode, and an object is freed the moment nothing points at it. The habit being replaced is reaching for a thread pool when a program is slow. In Python the right question is first: is it waiting, or is it computing?

Optional depth — but it makes three course-relevant facts click. When you run python3 app.py, CPython compiles your source to bytecode (cached in __pycache__/*.pyc, which is why second runs start faster), then a bytecode interpreter — the Python Virtual Machine — executes it one instruction at a time. So Python is compiled and interpreted, like Java without the JIT tier.

app.py source parse compiler emit bytecode cached in .pyc run PVM eval loop one op at a time GIL: only one thread executes bytecode at any instant 1 2 3 4
Fig. A1.4 — CPython's pipeline: source → bytecode → eval loop. The GIL serializes the last stage across threads.
  1. Your source. The file you wrote, read once from disk. Nothing in it is executed at this stage; it is parsed into a tree first, which is where a syntax error is reported, before a single line of your program has run.
  2. The bytecode. A list of small instructions for a stack machine, the same idea as JVM bytecode. It is cached in __pycache__ next to the file, which is why the second run of an imported module starts faster. The disassembly at the end of this section prints these instructions for a one-line function.
  3. The eval loop. A loop in C that fetches one instruction, does it, and fetches the next. This is where your program actually runs, and it is also where Python's reputation for slowness comes from: every addition is a trip around this loop, with type checks on the way.
  4. The lock. The Global Interpreter Lock is a mutex around that loop. One thread holds it at a time, so two threads never execute Python instructions at the same instant. It is released while a thread waits on the network or the disk, which is the difference that decides whether threads help you at all.

Now the same pipeline a second time, with this page's actual files in the boxes. If a stage in Fig. A1.4 feels abstract, find its row here: every stage is something you have already run on this page, or will run in Module 01.

Fig. A1.4 again, concretely: each stage as it exists on this page and in a uv project
StageRunning one file by hand (sections 03 to 07)In a uv project (section 08, Module 01)What flows out
Pick the interpreterWhatever python3 is first on your PATHuv pins the version in the project and uv run selects itOne known Python version
Resolve packagesNothing: every tour script is stdlib onlyuv add httpx "pydantic>=2.7,<3" writes pyproject.toml and uv.lockA venv that matches the lockfile on every machine
Parse and compilepython3 collections_tour.py compiles the file to bytecode in memoryThe same; imported modules cache their bytecode in __pycache__/Bytecode, the instructions dis shows below
Importimport metrics runs metrics.py once and stores it in sys.modulesThe same; the __main__ guard keeps self-tests out of importsModule objects, one per file
ExecuteThe eval loop runs one instruction at a time under the GILThe same, plus asyncio for network waits and processes for CPU workPrinted output, files, API calls
Check typesNone: typing_tour.py runs with its hints ignoreduv run mypy . before commit and in CIErrors caught before the program runs
Free memoryReference counting frees an object when its last name goes awayThe same; with blocks make file and connection release deterministicMemory returned, files closed

Memory: CPython frees objects primarily by reference counting — every object carries a count of names/containers pointing at it, and hits zero → freed immediately (that deterministic cleanup is why with blocks feel so predictable). A backup cycle collector (gc) sweeps up reference cycles that counting alone can't reclaim. That's the whole story at course depth.

The GIL, in three sentences. The Global Interpreter Lock lets only one thread execute Python bytecode at a time, so threads give you concurrency (useful while waiting on I/O, since the GIL is released during blocking calls) but not CPU parallelism.

That's why Module 01 teaches the rule: async for I/O-bound work (LLM calls are 99% waiting on the network) and processes for CPU-bound work (each process gets its own GIL).

Python 3.13+ ships an experimental free-threaded build, but as of Aug 2026 the async-vs-processes rule is still how production AI code is written.

Both halves of that rule are measurable, so here they are measured. The top of the picture is waiting work, which is what an LLM call is. The bottom is computing work, which is where the lock from marker 4 of Fig. A1.4 decides the outcome.

1 WAITING WORK: ONE THREAD, THREE AWAITS, MEASURED call A: await — 2 s of waiting call B: await — 2 s of waiting call C: await — 2 s of waiting one thread, switching to whichever call is not waiting the same three calls without await, one after another 0 s 2 s 4 s 6 s with await: 2.00 s without: 6.01 s 2 COMPUTING WORK: TWO THREADS, ONE LOCK the lock is handed over at each dashed line — only its holder runs bytecode thread 1 thread 2 shaded = running blank = waiting the same two 6-million-step loops, timed three times on one machine: one after the other: 0.62 s in two threads: 0.92 s to 1.76 s — never faster, sometimes twice as slow in two processes: 0.32 s — two cores, two interpreters, two locks
Fig. A1.4b — The rule, measured: three awaited calls finish in 2.00 s instead of 6.01 s, while two threads doing arithmetic finish no faster than one and two processes finish in half the time.
  1. Waiting work. Each bar is a call that spends its two seconds waiting for a reply. await lets the one thread start the next call instead of sitting still, so all three bars overlap and the whole thing takes as long as the slowest one. The same three calls without await lie end to end and take 6.01 s. No extra threads, no locks, and this is the shape of every batch of LLM requests in this course.
  2. Computing work. The shaded blocks are the moments a thread is actually running instructions, and they never overlap, because the lock is handed over at every dashed line. Two threads therefore finish no sooner than one, and the hand-offs cost real time, which is why the threaded run came out slower than the serial one. Two processes have two interpreters and two locks, so they genuinely halve the work.
  3. The rule you take away. Ask what the program is doing while it is slow. If it is waiting, use async and one thread. If it is computing, use processes, or push the loop into a library that does the arithmetic in C, which is what numpy and PyTorch are. Threads are for waiting, and only for waiting.

"One bytecode at a time, one thread at a time, and a reference count on every object. Why is Python so slow, and why does the entire AI industry use it anyway?"

— a Go engineer who just read Fig. A1.4

Both halves of the question are fair. A loop written in plain Python runs ten to a hundred times slower than the same loop in Go or Java. Every add is a trip through the eval loop, with type checks on the way. That cost is real, and a faster machine only hides it.

The industry uses Python because the slow part is almost never Python. The matrix multiply inside numpy or PyTorch runs in C, C++ and CUDA; the Python line that called it was one instruction. An LLM application spends its life waiting for the network, and a language that waits well, with asyncio, beats one that computes fast. Python is the glue, and glue is where the libraries and the hiring are.

The honest downside: leave the libraries and write a hand-rolled loop over a million records, and you pay the full price. Marker 2 of Fig. A1.4b is that price with a stopwatch on it: the same arithmetic took 0.62 s in one thread and 0.92 to 1.76 s in two, because the lock is handed back and forth instead of the work being shared. The fixes are real but they are extra work. Push the loop into numpy, move it to a process pool, or write that one hot function in Rust. Module 01 shows the first two.

Questions you might be asking now

The bubble above ends on "push the loop into numpy" as if that phrase explained itself. The questions below slow down for it. Every answer starts from the same three latencies, then scales up to the million values of Fig. A1.2b and timed.py.

The three latencies every answer below uses, taken from the tickets in iteration_tour.py. The last column is the job the answers give to both a list and an array: convert milliseconds to seconds.
Ticketprioritymsms ÷ 1000, in seconds
T-101high4,2004.2
T-102low9500.95
T-103high3800.38
Is a Python list the same thing as a numpy array?

No. A list is a row of arrows to separate Python objects, and every one of those objects carries its own type and bookkeeping. A numpy array is one block of raw numbers that all share a single type. For the million values of Fig. A1.2b that is 36,448,728 bytes as a list against 8,000,112 bytes as an array, 4.56 times smaller.

Start from what you already know. Fig. A1.2b split the list's memory into two pieces: the slots, and the million integer objects the slots point at. A numpy array keeps no per-number objects at all. It stores the numbers themselves, side by side, as 8-byte machine integers.

In Java terms, a numpy array of integers is a long[]. A Python list is closer to an ArrayList<Long>: a row of references to boxed numbers. numpy is the third-party package for arrays of numbers that the AI stack stands on: pandas and scikit-learn are built on it, and PyTorch's tensors use the same design.

Here are the bytes for the three latencies, counted by hand and then checked with sys.getsizeof by list_vs_numpy.py.

  1. The list object. A 56-byte header, plus room for 4 slots at 8 bytes each: 56 + 4 × 8 = 88 bytes. The literal [4200, 950, 380] keeps one spare slot for the next append.
  2. The three int objects. Each one is 28 bytes: an 8-byte reference count, an 8-byte pointer to its type, an 8-byte size field and 4 bytes of digits. 3 × 28 = 84 bytes.
  3. The list's total. 88 + 84 = 172 bytes, spread over 4 separate objects.
  4. The array. A 112-byte header, holding the array's bookkeeping: its shape, its type and where its data starts. Then the three numbers as 8-byte cells: 112 + 3 × 8 = 136 bytes, all in 1 object.
  5. Scale it up. Each header is paid once; the per-number cost is what grows. That is about 8 + 28 = 36 bytes per value for the list, against 8 for the array. For the million values of Fig. A1.2b: 8,448,728 + 28,000,000 = 36,448,728 bytes, against 8,000,112.
1 THE LIST [4200, 950, 380]: 172 BYTES IN 4 OBJECTS list header 56 B slot: 8 B slot: 8 B slot: 8 B spare: 8 B 4200 950 380 int: 28 B int: 28 B int: 28 B list object: 56 + 4 × 8 = 88 B 3 int objects: 3 × 28 = 84 B total: 88 + 84 = 172 B each int object: reference count 8 B + type pointer 8 B + size field 8 B + digits 4 B = 28 B 2 THE ARRAY np.array([4200, 950, 380]): 136 BYTES IN 1 OBJECT array header: 112 B shape · dtype int64 · data start 4200 950 380 8 B 8 B 8 B 112 + 3 × 8 = 136 B no int objects: the cells are the numbers three cells side by side, one type for all of them, no arrows to follow 3 THE SAME MILLION VALUES AS FIG. A1.2b, ON ONE SCALE list 36,448,728 B: 8,448,728 of slots + 28,000,000 for a million int objects array 8,000,112 B: 4.56 times smaller
Fig. A1.4e — The same three latencies stored two ways, with every byte accounted for, and then the million values of Fig. A1.2b on one scale. Byte counts are CPython 3.12 on a 64-bit machine, from rerunning list_vs_numpy.py.
  1. Four objects for three numbers. The list itself is a header and a row of 8-byte slots, with one spare kept for the next append. Each slot holds an arrow, and each arrow lands on a separate 28-byte int object. That is Fig. A1.1b again: a list holds arrows, not numbers.
  2. One object, raw numbers. The array's header records the shape, the type and where the data starts. The data is three 8-byte cells holding 4200, 950 and 380 directly. There is no object per number, so there is no type to check per number either, which is what the next question is about.
  3. Why the gap grows. At three values the header dominates: 172 bytes against 136. At a million values the headers are noise, and the per-value cost decides it: about 36 bytes against 8. The list bar is the same 36,448,728 bytes drawn in Fig. A1.2b.

The difference is not only memory. The same symbols mean different things on the two types, and the last row of this table is the one that bites people:

The same line on a list and on an array, as list_vs_numpy.py printed it (ms = [4200, 950, 380], arr = np.array(ms))
You writeOn the list msOn the array arr
+ itselfms + ms joins: [4200, 950, 380, 4200, 950, 380]arr + arr adds each pair: [8400 1900 760]
* 2Repeats the list: the same six itemsDoubles each number: [8400 1900 760]
/ 1000TypeError: unsupported operand type(s)[4.2 0.95 0.38]
A mix of typesFine: each slot points at any objectnp.array([4200, "slow"]) turns both into strings: ['4200', 'slow']
Grow by onems.append(5100) changes the list itselfnp.append(arr, 5100) returns a new array; arr still has 3
Slice, then writems[0:2] is a new list; writing to it leaves ms alonearr[0:2] is a view; writing 0 into it changed arr to [0 950 380]

That last row matters for this page in particular. Fig. A1.1c promised that a slice always hands back a new list, and for lists it does. An array slice is a view: a second arrow into the same block of numbers, so np.shares_memory printed True. When you mean a copy, write arr[0:2].copy().

The array is not simply the better list. It gives up what made the list useful: any mix of types, cheap appends, and a None in the middle. np.array([4200, None]) quietly becomes dtype object, which is a row of arrows again, with none of the savings.

Size matters too. For three values the gain is 172 bytes against 136. The array pays off when there are many numbers of one type: a column of latencies, an embedding, an image.

A list stores arrows to objects; an array stores the numbers themselves, in one block, with one type. Same brackets, different + and *, and an array slice is a view, not a copy.

What does "vectorised" actually mean? Show me a loop against one numpy line, measured.

Vectorised means you write one operation for the whole array, and the loop over the elements runs inside numpy's compiled code instead of Python's eval loop. Take the sum of squares of 0 to 999,999. timed.py's generator shape took 67.3 ms of CPU time here, and (a * a).sum() took 3.19 ms: 21 times faster, with the same answer.

The word borrows the maths sense of a vector: a whole row of numbers treated as one thing. In code it means you stop writing the loop yourself. You say "divide every latency by 1,000" once, and numpy does the dividing.

The time goes where marker 3 of Fig. A1.4 said it would: the eval loop. vectorised_timing.py asks the dis module what the list comprehension [m / 1000 for m in ms] compiles to. These seven bytecode instructions repeat for every element:

  1. FOR_ITER asks the list for its next item.
  2. STORE_FAST puts that item in the name m.
  3. LOAD_FAST pushes m back onto the stack.
  4. LOAD_CONST pushes the constant 1000.
  5. BINARY_OP divides. First it looks at the types of both operands to find the right division. Then it builds a new float object for the result.
  6. LIST_APPEND puts that float into the result list.
  7. JUMP_BACKWARD goes back to step A for the next item.

For the three tickets that is 3 × 7 = 21 trips through the eval loop. For a million values it is 7,000,000. The array line arr / 1000 compiles to one BINARY_OP for the whole array. numpy checks the type once, then runs a loop written in C over the raw 8-byte cells from Fig. A1.4e.

Now the same idea on a real workload: the sum of squares from timed.py, whose own comment printed 61.0 ms on another machine. "Per value" is the total divided by the count. For the first row: 67.3 ms ÷ 1,000,000 = 0.0000673 ms, which is 67 ns (nanoseconds, billionths of a second).

Sum of squares of 0 to 999,999; every line gives 333,332,833,333,500,000. Best of 9 runs in CPU time, measured by vectorised_timing.py on one laptop processor (Python 3.12.3, numpy 2.5.2); yours will differ.
LineCPU timePer valueWhere the loop runs
sum(i * i for i in range(n)), timed.py's shape67.3 ms67 nsPython's eval loop
for i in range(n): t += i * i62.8 ms63 nsPython's eval loop
sum([i * i for i in range(n)])89.0 ms89 nsPython's eval loop, plus a million-item list
(a * a).sum(), with a = np.arange(n)3.19 ms3.2 nsnumpy's C loop, twice
np.dot(a, a)0.81 ms0.8 nsOne C loop, no temporary array
1 [m / 1000 for m in ms]: THE EVAL LOOP RUNS SEVEN INSTRUCTIONS PER ELEMENT FOR_ITER STORE_FAST LOAD_FAST LOAD_CONST BINARY_OP LIST_APPEND JUMP_BACKWARD 7 instructions for every element: 21 for three tickets, 7,000,000 for a million values each BINARY_OP looks up both operands' types, then builds a new float object for the result 2 arr / 1000: ONE INSTRUCTION FOR THE WHOLE ARRAY BINARY_OP, once numpy's compiled loop: 4200 → 4.2, 950 → 0.95, 380 → 0.38 numpy checks the type once, then divides raw 8-byte cells with no Python objects in between 3 SUM OF SQUARES OF 0 TO 999,999: CPU TIME ON ONE MACHINE, SAME ANSWER ON EVERY ROW sum(i * i for i in range(n)) 67.3 ms · 67 ns per value for loop, t += i * i 62.8 ms · 63 ns per value sum([i * i for i in range(n)]) 89.0 ms · 89 ns per value (a * a).sum() 3.19 ms · 3.2 ns per value np.dot(a, a) 0.81 ms · 0.8 ns per value every row prints 333,332,833,333,500,000; (a * a).sum() is 21 times faster than the generator, np.dot 83 times
Fig. A1.4f — Why one numpy line beats a Python loop. Top: the seven instructions Python repeats per element. Middle: the one instruction numpy needs for the whole array. Bottom: the gap, measured on the sum of squares from timed.py. Values from rerunning vectorised_timing.py; CPU times are one machine's.
  1. Seven instructions per value. The row of boxes is what dis printed for the loop inside [m / 1000 for m in ms]. The return arrow sends the eval loop back to FOR_ITER for every element. Each BINARY_OP inspects both operands' types before it can divide, and every result is a new float object. That is 21 trips for three tickets.
  2. One instruction for all of them. arr / 1000 is a single BINARY_OP as far as Python can see. It hands the whole array to numpy, which checks the type once and runs a compiled loop over the raw cells drawn in Fig. A1.4e. The work per value is one division and nothing else.
  3. The measured gap. The three red bars run through the eval loop and land between 63 and 89 ns per value. The green bars run in C: 3.2 ns, and 0.8 ns when np.dot multiplies and adds in one pass. On your machine every bar will be a different length, but the gap between red and green will still be there.

Why is (a * a).sum() not the fastest? It is two vectorised steps. a * a builds a whole new 8 MB array of squares, and then .sum() walks it. np.dot(a, a) multiplies and adds in one pass, with no temporary array, which is why it was about four times faster again.

Two honest limits. First, vectorised does not mean parallel: every line in the table ran on one core. The speed comes from skipping the per-value bytecode, type checks and new objects, not from extra processors. Second, it only works when the whole job can be said as array operations. The next question is about the cases where it cannot.

Vectorised means the loop moves out of Python's eval loop into numpy's compiled code: you write one operation, numpy checks the type once and runs through raw numbers. Same answer, here 21 to 83 times faster.

So should every loop become numpy? Where does it not help?

No. numpy wins when one operation covers many numbers of one type. It loses on short lists, on Python loops that walk an array one element at a time, and on anything that grows item by item. Its fixed-size integers can also overflow without a word: summing the squares of 10 million values gave 1,291,890,006,563,070,912, a wrong answer, with no warning.

Every numpy call has a fixed cost before it touches a single number: read the arguments, check the types, allocate the result. On a big array that cost disappears into the work. On three latencies it is the work. Here is the ms-to-seconds job at six sizes, from the three tickets up to a million values.

[m / 1000 for m in ms] against arr / 1000, CPU time per call in µs (microseconds, millionths of a second), best of 9, from vectorised_timing.py. The last column adds np.array(ms) first, for when the numbers arrive as a Python list.
LatenciesList comprehensionnumpy, array already builtnumpy, converting the list first
30.1 µs1.4 µs1.8 µs
300.8 µs1.4 µs2.7 µs
1002.7 µs1.4 µs4.7 µs
1,00026.2 µs2.3 µs31.9 µs
100,0002,610.6 µs65.6 µs3,017.6 µs
1,000,00044,150.0 µs2,389.5 µs31,965.4 µs

Read the table in two ways. If the array already exists, numpy overtakes the list somewhere between 30 and 100 values. For the three tickets, the list comprehension took 0.1 µs against numpy's 1.4 µs.

If the numbers arrive as a Python list and you convert them for one operation, the conversion eats the gain. np.array(ms) has to visit every Python int object, which is the slow part all over again. The list comprehension stayed faster all the way to 100,000 values, and numpy won only at a million.

ms TO SECONDS: CPU TIME PER CALL AGAINST THE NUMBER OF LATENCIES, BOTH AXES LOG SCALE 0.1 µs 1 µs 10 µs 100 µs 1 ms 10 ms 100 ms 1 10 100 1,000 10,000 100,000 1,000,000 number of latencies (each tick is 10 times the last) list comprehension [m / 1000 for m in ms] numpy, array already built: arr / 1000 numpy, list arrives: np.array(ms) / 1000 1 · array ready: numpy wins between 30 and 100 2 · list arrives: numpy wins only near 1,000,000 1 2 3 A PYTHON LOOP OVER THE MILLION-VALUE ARRAY: EACH ELEMENT BECOMES A numpy.int64 OBJECT over the list 45.1 ms over the array 120.8 ms: 2.7 times the list loop 4 GROWING 20,000 ITEMS ONE AT A TIME: np.append COPIES THE WHOLE ARRAY ON EVERY CALL list.append 0.34 ms np.append 71.1 ms: 211 times longer 5 SUM OF SQUARES OF 0 TO 9,999,999: int64 WRAPS AROUND AND SAYS NOTHING Python int : 333,333,283,333,335,000,000 numpy int64: 1,291,890,006,563,070,912 no warning, no error
Fig. A1.4g — Where numpy stops helping. Top: the fixed cost of a numpy call against the per-element cost of a list comprehension, from 1 latency to a million. Bottom: three measured cases where reaching for numpy makes things slower or wrong. Values from rerunning vectorised_timing.py; CPU times on one machine.
  1. Array ready. The green line is flat on the left: about 1.4 µs whether it divides 1 latency or 100. That flat stretch is numpy's fixed cost per call. The list comprehension starts near 0.1 µs and grows with every element, so it crosses the green line between 30 and 100 values.
  2. List arrives. The dashed line is the green one plus np.array(ms). Converting visits every Python int, so the dashed line grows at the same rate as the list comprehension and runs just above it. It dips below only at a million values: 32.0 ms against 44.2 ms.
  3. Looping over an array. Each element taken out of an array is wrapped in a new numpy.int64 object, and arithmetic on those is slower than on plain ints. The same sum(x * x for x in …) took 120.8 ms over the array and 45.1 ms over a list.
  4. Growing one at a time. An array's block of cells cannot grow in place, so every np.append builds a new array and copies everything into it. The list's append uses the spare slots a list keeps for exactly this.
  5. Overflow. The true sum needs 69 bits; an int64 has 64, and keeps only the remainder. A Python int grows as needed, so the plain Python loop got the exact answer, only more slowly.

The overflow, by hand

A Python int grows as large as it needs to. A numpy int64 holds at most 9,223,372,036,854,775,807, and past that it wraps around, exactly like a Java long. Here is the check, with every step:

  1. The formula. 0² + 1² + … + (n − 1)² = (n − 1) × n × (2n − 1) ÷ 6.
  2. Plug in n = 10,000,000. 9,999,999 × 10,000,000 × 19,999,999 ÷ 6 = 333,333,283,333,335,000,000. Python's plain loop printed exactly this.
  3. Compare with the int64 limit. About 3.3 × 10²⁰ against about 9.2 × 10¹⁸: the true sum is about 36 times too big to fit.
  4. Wrap around. An int64 keeps only the remainder after removing whole multiples of 2⁶⁴, which is 18,446,744,073,709,551,616. The true sum holds 18 of them: 333,333,283,333,335,000,000 − 18 × 18,446,744,073,709,551,616 = 1,291,890,006,563,070,912.
  5. Compare with numpy. numpy printed 1,291,890,006,563,070,912: the remainder, digit for digit, with no warning.

The fixes are choices you make on purpose. Use float64 when an approximate answer is fine; it printed 3.333333e+20. Keep the sum in Python ints when it must be exact. And know your largest value before you pick an integer type.

Reach for numpy when one operation covers many numbers of one type and the array already exists. For a handful of values, element-by-element loops, one-at-a-time growth or integers that may pass 9.2 × 10¹⁸, stay with plain Python or choose the dtype on purpose.

See the actual bytecode — optional depth

The dis module disassembles any function. For def f(x): return x * 2 + 1, CPython 3.12 emits a load, two constant loads, and two binary ops — a stack machine, like the JVM:

Step-by-step: what bytecode_peek.py does, in plain English
  1. Import dis, the standard library's disassembler.
  2. Define a one-line function so there is something small to inspect.
  3. Call dis.dis(f). It prints every bytecode instruction the compiler produced: load x, load the constant 2, multiply, load the constant 1, add, return. The comment lines show the 3.12 output; other versions print slightly different names and offsets.
bytecode_peek.pyruns offline
# stdlib only -- run with: python3 bytecode_peek.py  (3.12 output; yours may differ)
import dis

def f(x):
    return x * 2 + 1

dis.dis(f)
#   0 RESUME       0
#   2 LOAD_FAST    0 (x)
#   4 LOAD_CONST   1 (2)
#   6 BINARY_OP    5 (*)
#  10 LOAD_CONST   2 (1)
#  12 BINARY_OP    0 (+)
#  16 RETURN_VALUE

Each of those instructions is one trip through the eval loop — and the GIL is exactly a mutex around that loop. "One bytecode at a time" is literal.

12 · The road aheadThe Python You'll Meet in This Course

That is the language. This section is the receipt. Marcus lost three weeks because five spellings arrived in the same screenful; the point of what follows is that from here they arrive one at a time, each inside a module that needs it for a job. The habit being replaced is learning a language front to back and hoping the useful parts turn up. Every construct below was chosen because a later module cannot be read without it.

Everything above was chosen backwards from the course itself. Here's the map from construct to the first place it carries real weight — when you hit one of these modules and a shape looks familiar, that's this appendix paying out:

Construct → where it first appears in the course
ConstructDoing whatFirst appears
ComprehensionsEvery data-shaping lineEverywhere, from Module 01
Pydantic modelsData contracts; LLM structured outputsM01 · M06
async / awaitConcurrent LLM callsM01 · M06
Decoratorspytest fixtures; FastMCP tools; FastAPI routesM07 · M10 · M12
DataclassesAgent stateM09
Context managersStreaming LLM responses safelyM06
Type hintsLetting mypy check LLM-generated codeM15 (and every lab)
1 WHERE EACH CONSTRUCT FIRST CARRIES REAL WEIGHT 2 comprehensions Pydantic models async / await context managers 3 pytest fixtures dataclasses for agent state FastMCP tools FastAPI routes 4 type hints check LLM-written code M01 M06 M07 M09 M10 M12 M15 the course order runs left to right; nothing below appears before the module it is drawn above three of the seven land in Module 01, which is the module Marcus bounced off
Fig. A1.4c — The same table as a timeline: seven constructs, and the module where each one stops being syntax and starts being the job.
  1. The line is the course. Left to right in reading order, with one dot per module that needs something from this page. Everything above a dot is what that module assumes you can already read.
  2. The Module 01 cluster. Three of the seven land immediately, in the module Marcus closed the tab on. That is not bad course design; it is what a working stack needs on day one. It is also why this appendix exists and why it sits before Module 00.
  3. The decorator appears three times. A test fixture, a tool definition and a web route are the same shape you built in Fig. A1.2c: function in, wrapped function out. Learn it once here and three later modules stop looking like framework magic.
  4. Type hints pay last and pay most. They cost you nothing at run time all the way through the course, and then become the thing that catches an LLM's mistakes in your repository. That is the one construct whose value is not visible when you learn it.
Boardroom translation

The honest fluency math: an engineer who reads Python natively reviews AI code — teammates' and LLM-generated alike — three to five times faster than one mentally transliterating from another language, because fluent readers chunk idioms instead of parsing tokens. And Python isn't one option among many here: it's the lingua franca of every tool in this course and appears in 91–96% of AI job postings (see the market page). The elevator version: "Six focused hours buys permanent fluency in the language every AI tool speaks — it's the cheapest multiplier on every hour that follows."

13 · The labBuild the Tool You'll Study With

Six hours should end with something running. The lab builds a flashcard trainer whose deck is this page's own five gotchas, so the thing Marcus builds is the thing that keeps the page in his head. Every construct in the specification is there because the job needs it: a dataclass for the card, a comprehension for the due list, a generator for the drill, a decorator for the timing, and forgiveness-not-permission for the corrupt file. The habit being replaced is the last one, learning a language by reading about it.

Worked examples first, spec second — you've seen every ingredient this lab needs, most of them in this page's own code blocks. Note the meta-trick: you're building a spaced-repetition trainer whose deck is this appendix's own gotchas — the tool you build is the tool you'll use to retain the page. Here's the seed script (your 80%); the scheduler and CLI are your 20%:

Step-by-step: what seed_deck.py does, in plain English
  1. Import json and Path.
  2. Define CARDS: five dicts, each with a front (the question) and a back (the answer). The five questions are this page's five gotchas.
  3. Build the deck with a comprehension over the cards. {**c, "streak": 0, "due": 0} copies each card's keys into a new dict and adds two scheduling fields. The double star here means "spread this dict's items in", like ...obj in JavaScript.
  4. Wrap the list in an outer dict with a version number, so the file format can change later without breaking old decks.
  5. Write it to deck.json in one call, indented so you can read the file, and print a confirmation with an f-string.
seed_deck.pyruns offline
# stdlib only -- run once:  python3 seed_deck.py
import json
from pathlib import Path

CARDS = [
    {"front": "def f(x, acc=[]) -- what's wrong?",
     "back": "The [] is created once at def time; every call shares it. Use acc=None."},
    {"front": "[lambda: i for i in range(3)] -- each call returns?",
     "back": "2. Closures look i up at call time (late binding). Capture with i=i."},
    {"front": "list(grid) copies what, exactly?",
     "back": "The outer list only -- inner lists are shared. That's a shallow copy."},
    {"front": "0.1 + 0.2 == 0.3?",
     "back": "False -- binary floats. Compare with math.isclose."},
    {"front": "a is b vs a == b?",
     "back": "is = same object (identity); == = same value. Use is only for None."},
]

deck = {"version": 1, "cards": [{**c, "streak": 0, "due": 0} for c in CARDS]}
Path("deck.json").write_text(json.dumps(deck, indent=2))
print(f"seeded deck.json with {len(CARDS)} cards")   # seeded deck.json with 5 cards
deck.json 5 cards, streak 0 1 load_deck() missing file → a hint corrupt JSON → ValueError 2 list[Card] @dataclass, fully hinted 3 due today one comprehension the cards that are due, handed on to the drill 4 yield one card a generator: the deck is never copied to drill it 5 @timed drill front · Enter · back · y/n a decorator reports the time y → streak + 1 due = now + 2**streak days n → streak back to 0 write deck.json tomorrow's run starts here again, and the due filter picks a different set Streak 0 means due now; after three correct answers in a row the card is next due in 2³ = 8 days. Five cards, and the acceptance test is you: drill once a day and by day three you clear all five from memory.
Fig. A1.4d — The lab in one picture: each box is one construct from this page, doing the job that made it worth learning.
  1. Loading, forgiveness style. The risky lines go in the try: reading the file and parsing it. A missing file is a normal state and gets a helpful message; corrupt text becomes a ValueError that names the file. This is Fig. A1.2e with your own file name in it.
  2. The card is a dataclass. Front, back, streak, due, all typed. You get the constructor, the printer and field-by-field equality for free, and mypy can check every function that touches a card.
  3. One comprehension picks the due cards. Filter on the due date, keep the card. One line, no accumulator, and the intent is readable in review: these are the cards due today.
  4. The generator hands them out. The drill walks the due cards once, in order, so a generator is the honest shape, and marker 6 of Fig. A1.3b says so. Note what you give up: no len(), so if you want to print "card 3 of 7" you need the list as well.
  5. The decorator times the drill. Exactly the ten lines you read in timed.py, applied to your own function. It is also where the spaced-repetition arithmetic lands: a correct answer pushes the next showing out to two to the power of the streak, in days.
LAB A1 — flashcards.py, a spaced-repetition CLI (stdlib only)

Mission: build flashcards.py so that python3 flashcards.py drill shows each due card's front, waits for Enter, reveals the back, and asks "got it? [y/n]" — y bumps the card's streak and pushes its due date out (e.g. due = now + 2**streak days), n resets the streak to 0. State persists to deck.json between runs. Every construct below must appear because the job needs it, not as decoration.

  • Card is a @dataclass with full type hints; deck round-trips to deck.json via pathlib + json
  • Due-card selection is a single comprehension over the deck
  • At least one generator used meaningfully (e.g. lazily yielding due cards to the drill loop)
  • At least one decorator used meaningfully (e.g. @timed on the drill, or a @requires_deck guard that seeds a missing file)
  • Malformed deck handled EAFP-style: missing file → helpful "run seed_deck.py" message; corrupt JSON → ValueError naming the file, no raw traceback
  • Measurement criterion: uv run mypy flashcards.py exits clean (zero errors)
  • Self-test: drill the deck once a day for three days; by day three you should clear all five gotchas from memory — that's the acceptance test for you, not just the code

Stretch goal: a pytest suite covering the scheduler's edges (streak reset, empty deck, all-cards-future), plus a --stats flag printing a streak histogram built with a dict comprehension.

14 · Interview radarHow This Shows Up in Interviews

Interview radar

Python screening questions show up even in AI-focused loops — usually in the first 15 minutes, as fluency checks. These five are the perennials:

"What's wrong with def f(x, items=[])?"

Strong answer The default is evaluated once, at def time, and stored on the function object — so every call that uses the default shares one list. Call f(1) twice and the second call sees whatever the first appended. The fix is a None sentinel that creates a fresh list inside the body, or default_factory in dataclasses.

Land it The bonus point: it's harmless with immutable defaults — the trap is specifically mutable ones.

"List vs tuple vs set — when and why?"

The real test Contracts, not trivia — can you say what each choice promises the reader?

Strong answer Each structure is a different contract:

  • List is an ordered, growable sequence — the default when the collection can change size
  • Tuple is a fixed-shape record: immutable, and therefore hashable, which is what lets it serve as a dict key
  • Set buys O(1) membership tests and uniqueness, at the cost of order

Land it Choosing a tuple for a record signals "this shape is fixed" to readers — the choice communicates, not just computes.

"Generator vs list — what's the actual trade?"

Strong answer The trade is memory and laziness against reusability. A generator holds one element alive at a time and computes values on demand, which is exactly what streaming and huge files need — but it is single-pass and has no len(). A list costs full materialization up front, and in exchange buys random access and the ability to iterate again.

Land it Cite a real case: streaming LLM tokens as they arrive is generator territory; collecting a result list you'll re-read is a list. The deciding rule is two lines long.

"What does the GIL actually prevent?"

The real test Precision — can you name exactly what is serialized, and what isn't?

Strong answer The GIL serializes bytecode execution across threads, so it kills CPU parallelism but not I/O concurrency. The lock is released during blocking I/O, which is why threads and async still help for network-bound LLM work — a thread waiting on an API response isn't holding the GIL. For CPU-bound work, processes are the answer.

Land it Mention the 3.13+ free-threaded build as experimental — it shows currency.

"is vs ==?"

Strong answer is asks whether two names point at the same object — identity — while == asks whether two values are equal. Reserve is for singletons like None; everything else gets ==.

Land it The judgment-check follow-up is "why does x is 1000 sometimes work?" — small-int caching, an implementation detail you should name and refuse to rely on.

Quick reference — Python fundamentals

Choosing the Python toolchain
Standard library first, uv for the project, mypy for hints, Pydantic where data crosses a border, NumPy for big number arrays. Add each one only when its problem shows up.
Names are references
A name points at an object; it does not contain it. Assignment rebinds the name and copies nothing — which explains most surprising Python behaviour.
The mutable default trap
A default argument is evaluated once, at definition. def f(x=[]) shares one list across every call. Use None.
iteration protocol
Anything with __iter__ can be looped over. A generator produces values lazily, one at a time, and never builds the whole list. Which one to reach for comes down to two lines.
comprehensions
The idiomatic way to build a list, dict or set from another iterable. Read them as “what I want, for each thing, when a condition holds”.
EAFP
Easier to ask forgiveness than permission — try it and catch the error, rather than checking first. This is Python's style, not a shortcut.
context manager
with guarantees cleanup even when something raises. Use it for every file, connection and lock.
GIL
One thread runs Python bytecode at a time. So: threads or async for I/O-bound work, processes for CPU-bound work — the rule, measured.
Passing an argument
A call runs parameter = argument, so the function gets a second arrow to your object. Mutations are shared; rebinding is private, and nothing is copied.
+= on a list
Extends the same object, so every name sees the new item; x = x + y builds a new list. On an int, a str or a tuple, += always builds a new object.
numpy array
One block of raw numbers of one type. About 4.5 times smaller than a list of the same ints; its + adds, and its slices are views.
vectorised
One operation for the whole array, looped in numpy's compiled code instead of Python's eval loop. It loses on a handful of values, on element-by-element loops and on one-at-a-time growth.

15 · RecapWhat You Can Do Now

  • You can choose list, tuple, dict, or set deliberately — and defend the choice in review
  • You can read and write comprehensions, enumerate/zip, and sorted(key=…) at full reading speed
  • You can explain the iteration protocol and write a generator, knowing exactly when its body runs
  • You can build a decorator from scratch — and recognize the shape in pytest, FastMCP, and FastAPI before those modules introduce it
  • You can model data with @dataclass and say precisely when Pydantic earns its install
  • You can handle errors EAFP-style with narrow excepts and chained raises, and explain what with guarantees
  • You can annotate a function fully and run mypy clean — the habit every course lab assumes
  • You can name all five classic gotchas from memory and spot them in someone else's diff
  • You can say exactly what a function receives when you pass it a list, and predict whether the caller will see the change
  • You can explain why one numpy line beats a Python loop, and name the cases where it does not
🧠 Flex your memory

From this appendix: close the page and write, from memory, the mutable-default gotcha and both fixes (the None sentinel and default_factory) — then check yourself against gotchas.py. And a forward reference: open Module 00 and find Fig 0.1 — the inversion diagram, the course's first real idea. Read it and the code beneath it. Every Python construct in that code is now one you know. You're ready to read it.