All courses
Courses › How LLMs really work · foundation

Reading Python

Read short Python: lists, dicts, functions, loops, comprehensions, f-strings, imports.

▶ Watch this lesson Start the whole course

What the animation says

Blocks and lists

Later lessons show ideas as short Python snippets. If you can read them, you can run every claim yourself. Python has no braces. Indentation marks a block: lines pushed in under def, for or if belong to it. A list holds items in order, counted from zero. So a, index zero, is ten. Minus one counts from the end: a, index minus one, is thirty, the last item. A slice takes a range. Here is a, from zero to two. What comes out?

Dicts, = and ==

Ten and twenty. A slice stops before its end, and range of three runs zero, one, two, the same way. A dict looks up values by key. Here, the key cat gives three. Storing under a new key, like dog, adds it. Storing under cat again replaces its value. One equals sign stores a value under a name. Two equals signs only test, and give True or False. Plus-equals adds to the value already there, and double star means power.

Comprehensions

This loop builds a new list: for each x, if x is above zero, it appends x squared. A comprehension packs that whole loop into one line. Read it in this order: the for part, then the if test, then the expression at the front, which is what gets collected. Curly braces with a key, a colon and a value build a dict the same way. Now xs is three, minus one, four. What ends up in sq?

Trace it by hand

Nine and sixteen. Let's trace it by hand: x is three, which passes the test, so keep nine. x is minus one: the test fails, so skip it. x is four: keep sixteen. Now sq at minus one is the last item, sixteen. And its length is two. An f-string is text in which each pair of braces is replaced by a value. Here, sq at one divided by three is five point three three three. Colon, point one, f shows one decimal: five point three.

Counting words

Now a real snippet that counts words. Split cuts the text into words wherever there is whitespace. The get call returns a word's stored count, or zero if the word isn't there yet. This line adds one and stores the result back under that word. Watch the dict fill up: the, cat, saw, each with a count of one. Next comes the second the. Tap the entry it changes.

What it prints

The second the raised its count to two. Then dog arrives with one. Print shows the dict on screen, with single quotes around the text. Looping over a dict gives its keys, in the order they were added. This comprehension keeps the words seen once: three of them. Import math brings in the math module. The square root of the count for the, which is two, is one point four one four. To read any snippet, go top to bottom and keep track of each name's current value.

Why learn to read Python snippets?

Later lessons show ideas as short Python snippets: a few lines that compute something step by step. If you can read them like sentences, you can check every claim yourself by running it, instead of taking it on trust. So what do Python's core pieces mean (lists, dicts, functions, loops, comprehensions, f-strings, imports), and how do you trace a snippet in your head?

Containers, blocks and loops

- **Indentation** marks a block. Lines indented under `def`, `for` or `if` belong to it. Python uses no braces to mark blocks. - **List** `a = [10, 20, 30]` is ordered and counted from 0. `a[0]` is 10, `a[-1]` is the last item, and `a[0:2]` is `[10, 20]` (the end is excluded). - **Dict** `d = {"cat": 3}` looks up a value by its key: `d["cat"]` is 3. `d["dog"] = 5` adds that key, or replaces its value if the key is already there. - `def f(x): return x + 1` defines a function. - `for i in range(3):` runs with i = 0, 1, 2. - `if x > 0:` runs its block only when the test is true.

Compact forms you'll see everywhere

- **Comprehension** `[x * x for x in xs if x > 0]` is a loop packed into one line. For each x in xs, it keeps x only if the test passes and collects `x * x` into a new list. `{k: v for ...}` builds a dict the same way. - **f-string** `f"n={n:.2f}"` is text in which each `{...}` is replaced by a value. `:.2f` means show 2 decimals. - `import math`, then `math.sqrt(9)`. `import x as y` gives the module a shorter name. - `x = 5` stores a value under a name. `x == 5` only tests equality and gives True or False. - `x += 1` means `x = x + 1`. `**` means power.

Trace a snippet by hand

`xs = [3, -1, 4]` `sq = [x ** 2 for x in xs if x > 0]` 1. x = 3: 3 > 0, so keep 3² = 9. 2. x = −1: the test fails, so skip it. 3. x = 4: keep 16. So `sq = [9, 16]`. Then `sq[-1]` is 16 and `len(sq)` is 2. `f"{sq[1] / 3:.1f}"` gives the text `5.3`, because 16/3 = 5.333… shown with 1 decimal.

A real snippet: counting words

`text.split()` cuts the text into words wherever there is whitespace (such as spaces). `counts.get(w, 0)` returns the stored count for w, or 0 if w is not there yet. Looping over a dict gives you its keys, in the order they were added. `print` shows a value on screen; Python writes text inside a dict with single quotes. The program prints `{'the': 2, 'cat': 1, 'saw': 1, 'dog': 1}`, then `3 appear once; sqrt=1.414`.
import math

def count_words(text):
    counts = {}
    for w in text.split():
        counts[w] = counts.get(w, 0) + 1
    return counts

c = count_words("the cat saw the dog")
print(c)
once = [w for w in c if c[w] == 1]
print(f"{len(once)} appear once; sqrt={math.sqrt(c['the']):.3f}")

What to remember

Read Python top to bottom and keep track of each name's current value. Indentation tells you which lines belong together. Lists count from 0 and slices exclude their end. Dicts look up values by key, and `d[k] = v` stores a value under a key. `=` stores a value, while `==` tests equality. A comprehension is just a loop that collects results into a new list or dict.

On Bytewise this lesson comes in small steps with a check at the end, and the app brings it back right before you would forget it.