Read the code in this track in twenty minutes
The ladder of growth shapes. Every loop you learn to read here is one you can place on that ladder.
The Try-it box you cannot read
You open a lesson in this track and read the story. It makes sense. Then you reach a box of code near the end. It has a line like for x in nums: and you stop. You have never written code. You do not know what x is, why the next line is pushed to the right, or what nums[0] means.
That box is where the learning happens. Every lesson in this track ends with code you can run and change, and the code is written in Python.
The history (optional)
Python was written by Guido van Rossum at CWI, a research institute in Amsterdam. On 20 February 1991 (the date on his Usenet post, in US time) he posted version 0.9.0 to the newsgroup alt.sources, so that anyone could read and run it. Nothing in this lesson depends on that date.
By the end of this lesson you will be able to read any Try-it in this track line by line. You will say what every name holds after every line, and you will predict what the code prints before you run it.
Before you start. Everything Is a Number (bits & bytes) showed that a computer keeps every value as bits in memory, so a name in code is only a way to find one place in that memory. How Code Becomes Execution (compilers, stack & heap) showed that code is a list of steps the chip runs in order, which is exactly how this lesson asks you to read it. You need nothing else. If you have a way to run Python (a terminal with python3, or the free Python Tutor page in Go deeper), run each block as you go. The outputs below were produced by Python 3.12.3 on 2026-11-28.
Variable: a name that holds one value
Read these lines from top to bottom, one at a time.
price = 40
name = "tea"
print(name, price)
price = price + 10
print(price)
tea 40
50
A value is one piece of data, such as the number 40, or the text "tea". Text inside quotation marks is called a string. The sign = does not mean “is equal to”. It means “store the value on the right under the name on the left”. Line 1 stores 40 under the name price.
Line 4 is the line that surprises people. Python works out the right side first: 40 + 10 = 50. Then it stores 50 under price. The 40 is gone. print shows its values on the screen.
Think of a rack of steel dabbas, each with a name painted on its lid. The name is on the lid and the food is inside. Putting new food in a dabba throws out the old food. A variable is exactly this: a name that holds one value, and you can change the value any time. From now on this lesson says only “variable”.
To ask whether two things are equal, Python uses a double sign: price == 50 gives True. One = stores. Two == asks.
List: many values in order, counted from 0
nums = [3, 1, 4, 1, 5]
print(len(nums), nums[0], nums[4], nums[-1])
nums.append(9)
print(nums)
A list holds many values in a fixed order, written between square brackets. The position of a value is its index. The first value has index 0, not 1. len(nums) counts the values. nums[0] means “the value at index 0”.
A list holds 5 values. What is the index of its last value?
The first index is 0, so the indexes run 0, 1, 2, 3, 4. The last one is the length minus 1.
The last index is 5 − 1 = 4. So nums[4] is 5, the fifth value. A negative index counts from the end, so nums[-1] is always the last value, whatever the length. nums.append(9) adds 9 at the end, and the list grows to six values.
5 3 5 5
[3, 1, 4, 1, 5, 9]
The first line is len(nums), nums[0], nums[4] and nums[-1] in order. The second is the list after the append.
Loop: the same lines, once per value
total = 0
for x in nums:
total = total + x
print("x is", x, "total is", total)
print("sum", total)
A loop runs the same lines again and again. In for x in nums:, Python takes the values of nums one at a time and stores each in the variable x. The lines pushed to the right (indented) are the body, and they run once per value. The first line that is not pushed right runs after the loop has finished. In Python, the spaces at the start of a line are part of the meaning.
Here nums has six values, so the body runs six times. Follow total one step per line:
total starts at 0
x = 3: 0 + 3 = 3
x = 1: 3 + 1 = 4
x = 4: 4 + 4 = 8
x = 1: 8 + 1 = 9
x = 5: 9 + 5 = 14
x = 9: 14 + 9 = 23
x is 3 total is 3
x is 1 total is 4
x is 4 total is 8
x is 1 total is 9
x is 5 total is 14
x is 9 total is 23
sum 23
The same pattern with a count instead of a list is for i in range(3):. range(3) gives 0, 1, 2. It starts at 0 and stops before 3, so the body runs 3 times.
Dictionary: look up a value by its key
Some questions are not “what is at position 3” but “how many times did the letter a appear”. For those, a list is awkward.
count = {}
for ch in "banana":
count[ch] = count.get(ch, 0) + 1
print(count)
print(count["a"], "a" in count, "z" in count)
A dictionary holds pairs, written between curly brackets. In each pair the key is what you look up, and the value is what you get back. count["a"] means “the value stored under the key a”. You look up by key, not by position.
count.get(ch, 0) means “the value under ch, or 0 if ch is not a key yet”. The loop visits the letters of "banana" in order:
b: not there yet, 0 + 1 = 1
a: not there yet, 0 + 1 = 1
n: not there yet, 0 + 1 = 1
a: there, 1 + 1 = 2
n: there, 1 + 1 = 2
a: there, 2 + 1 = 3
How many times does the letter a appear in banana?
The word is b, a, n, a, n, a. The letter a sits in positions 2, 4 and 6.
The count for a ends at 3, for n at 2, and for b at 1. The expression "a" in count asks whether a key exists. It gives True for a and False for z.
{'b': 1, 'a': 3, 'n': 2}
3 True False
Function: a named block you can run on any input
def biggest(items):
best = items[0]
for x in items:
if x > best:
best = x
return best
print(biggest([3, 1, 4, 1, 5]))
print(biggest([-7, -2, -9]))
A function is a named block of lines. def biggest(items): creates it. The name items is its input, and it stands for whatever list you hand it. return best sends one answer back to the line that called it. The line if x > best: runs its body only when the question is true.
Trace the first call, where items is [3, 1, 4, 1, 5]:
best starts as items[0] = 3
x = 3: 3 > 3 is false, best stays 3
x = 1: 1 > 3 is false, best stays 3
x = 4: 4 > 3 is true, best becomes 4
x = 1: 1 > 4 is false, best stays 4
x = 5: 5 > 4 is true, best becomes 5
return 5
5
-2
The same function worked on a second list without any change. That is why functions exist: write the steps once, run them on any input.
That is the whole kit: variable, list, loop, dictionary, function. Every Try-it in this track is these five in a different order.
You now know
- A variable is a name that holds one value, and
=stores while==asks. - A list holds values in order, and its first index is 0, so the last index is the length minus 1.
- A loop runs its indented lines once per value, and you read it by following one variable per line.
- A dictionary looks up a value by key, and
.get(key, 0)gives 0 for a missing key. - A function is a named block with an input and a
return, and you trace it with the same one-line-at-a-time method. - You can read a Try-it by writing down what each name holds after each line.
Stop here if you want.
- Indexing: “What does
nums[len(nums)]do?” They want anIndexError, because the last index islen(nums) - 1, and a note thatnums[-1]is the safe way to get the last value. - Dictionary use: “Why store numbers you have seen in a dictionary and not a list?” They want the cost: a key lookup takes about one step on average, and a search through a list takes one step per value.
- Recursion: “What two parts must every recursive function have?” They want a base case that stops, and a call on a smaller input that moves toward it.
- Cost: “Why is
fib(n)written with two recursive calls slow?” They want the call count: it repeats the same work, andfib(30)makes 2,692,537 calls.
Common mistakes
- Writing
=where==is needed, which stores a value and does not ask a question. - Forgetting
return, so the function hands backNone(Python’s word for “no value”) and the next line fails. - Counting from 1 instead of 0, so every index is off by one.
Second read: the rest of the symbols, and a function that calls itself
Small symbols you will meet
nums = [3, 1, 4, 1, 5, 9]
n = 7
while n > 1:
n = n // 2
print("n", n)
print(7 // 2, 7 % 2, 2 ** 10, 7 / 2)
print([x * x for x in range(5)], nums[1:3])
a, b = 1, 2
a, b = b, a + b
print(a, b)
n 3
n 1
3 1 1024 3.5
[0, 1, 4, 9, 16] [1, 4]
2 3
# textis a comment. Python ignores it.while n > 1:is a loop that repeats as long as the question is true. Here 7 // 2 = 3, then 3 // 2 = 1, and 1 > 1 is false, so it stops.//divides and drops the fraction,%gives the remainder,**is a power, and/divides exactly. So 7 // 2 = 3, 7 % 2 = 1, 2 ** 10 = 1024 and 7 / 2 = 3.5.nums[1:3]is a slice: the values at indexes 1 and 2, and it stops before 3.[x * x for x in range(5)]builds a list by squaring each value. Read it as “x times x, for each x in range 5”.a, b = b, a + bworks out both right-hand values first, then stores them. That is why a was 1 and b was 2, and they became 2 and 3.elifmeans “otherwise if”.Nonemeans “no value”.enumerate(nums)gives the index and the value together.
Two errors, read as plain sentences
try:
print(nums[10])
except IndexError as e:
print("IndexError:", e)
IndexError: list index out of range
The list has six values, so indexes 0 to 5 exist and 10 does not. A dictionary asked for a missing key says the same thing in its own way: count["z"] gives KeyError: 'z'. The fix is .get or an in check first.
A function that calls itself: recursion, previewed
def countdown(n):
if n == 0:
print("liftoff")
return
print(n)
countdown(n - 1)
countdown(3)
def fact(n):
if n <= 1:
return 1
return n * fact(n - 1)
print(fact(5))
3
2
1
liftoff
120
A function may call itself, as long as two parts are present. The base case is the input where it stops and answers directly: n == 0 in countdown, n <= 1 in fact. The other part is a call on a smaller input, n - 1, so every call moves toward the base case.
fact(5) waits for fact(4), which waits for fact(3), and so on down to fact(1), which returns 1. Then the answers come back up the chain:
fact(1) = 1
fact(2) = 2 * 1 = 2
fact(3) = 3 * 2 = 6
fact(4) = 4 * 6 = 24
fact(5) = 5 * 24 = 120
flowchart LR A["fact(5) waits"] --> B["fact(4) waits"] --> C["fact(3) waits"] --> D["fact(2) waits"] --> E["fact(1) returns 1"] E -->|"2 * 1 = 2"| D D -->|"3 * 2 = 6"| C C -->|"4 * 6 = 24"| B B -->|"5 * 24 = 120"| A
Each waiting call is kept on the call stack, the list of unfinished calls (How Code Becomes Execution (compilers, stack & heap)). Python allows 1,000 of them by default (sys.getrecursionlimit() printed 1000 here). A function with no base case fails with RecursionError: maximum recursion depth exceeded.
Free problem 1: Two Sum (LeetCode 1)
Given a list of numbers and a target, return the indexes of the two numbers that add up to the target. Exactly one answer exists, and you may not use the same index twice. This problem is free, not premium.
For each value x, the partner we need is target - x. We keep a dictionary of values already seen, with their indexes.
def two_sum(nums, target):
seen = {}
for i, x in enumerate(nums):
need = target - x
print("i", i, "x", x, "need", need, "seen", seen)
if need in seen:
return [seen[need], i]
seen[x] = i
return []
print(two_sum([2, 7, 11, 15], 9))
i 0 x 2 need 7 seen {}
i 1 x 7 need 2 seen {2: 0}
[0, 1]
At index 1, the value is 7 and the partner needed is 9 − 7 = 2. The dictionary already holds 2 at index 0, so the answer is [0, 1]. Running the function without the print on two more LeetCode examples gave two_sum([3, 2, 4], 6) = [1, 2] and two_sum([3, 3], 6) = [0, 1].
The cost is one pass over the list, with one dictionary lookup per value, about one step each on average (Hashing). The slow way checks every pair: for 10,000 values that is 10,000 × 9,999 / 2 = 49,995,000 pairs, against 10,000 steps here. The full version is in Clinic #05: Two Sum.
Free problem 2: Fibonacci Number (LeetCode 509)
Return the n-th number of the sequence 0, 1, 1, 2, 3, 5, 8 and so on, where each number is the sum of the two before it. LeetCode’s input limit is 0 ≤ n ≤ 30. This problem is free, not premium.
calls = 0
def fib(n):
global calls
calls += 1
if n < 2:
return n
return fib(n - 1) + fib(n - 2)
memo = {}
mcalls = 0
def fibm(n):
global mcalls
mcalls += 1
if n < 2:
return n
if n in memo:
return memo[n]
memo[n] = fibm(n - 1) + fibm(n - 2)
return memo[n]
def fib_loop(n):
a, b = 0, 1
for _ in range(n):
a, b = b, a + b
return a
print(fib(10), calls)
print(fibm(10), mcalls)
calls = 0
print(fib(30), calls)
mcalls = 0
memo.clear()
print(fibm(30), mcalls)
print([fib_loop(k) for k in range(11)], fib_loop(30))
55 177
55 19
832040 2692537
832040 59
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55] 832040
All three give 832,040 for n = 30. The plain version made 2,692,537 calls, and the one with a dictionary of saved answers (memo) made 59.
Why so many? Calling fib(4) calls fib(3) and fib(2), and fib(3) calls fib(2) again:
flowchart TD F4["fib(4)"] --> F3["fib(3)"] F4 --> F2b["fib(2)"] F3 --> F2a["fib(2)"] F3 --> F1a["fib(1)"] F2a --> F1b["fib(1)"] F2a --> F0a["fib(0)"] F2b --> F1c["fib(1)"] F2b --> F0b["fib(0)"]
Count the boxes: 9 calls for n = 4. Each call adds one, plus the calls of its two children, so calls(n) = calls(n − 1) + calls(n − 2) + 1. With calls(0) = 1 and calls(1) = 1, that gives 1, 1, 3, 5, 9, and 177 at n = 10. The count grows by about 1.6 times per step, so it is exponential (Complexity & Big-O).
With the saved answers each value is worked out once. The 29 values from 2 to 30 are each worked out once, and each makes 2 calls: 29 × 2 = 58. Add the first call, fib(30) itself: 58 + 1 = 59. In general that is 2n − 1, so n = 10 gives 2 × 10 − 1 = 19. The loop version needs no calls at all and holds only two variables. The full story of saved answers is in Foundations #02: Recursion → Memo → Table (DP ka engine) and Recursion & Dynamic Programming.
Real systems
CPython, the usual Python, stores a list as an array that grows when full, so append is cheap on average, as measured in Complexity & Big-O. It stores a dictionary as a hash table, which is why a lookup by key takes about one step. Every lesson that follows uses those two structures in Python, and Arrays & Strings is the next to put them to work.
Try it
- Predict, then run. Without running, write what this prints, one line per loop step, then run it to check:
total = 10, thenfor x in [2, 5, 3]:with the bodytotal = total - x, thenprint(total). Do the subtraction one step per line. - Write a function. Write
smallest(items)that returns the smallest value in a list, copying the shape ofbiggest. Test it on[3, 1, 4, 1, 5](the answer is 1) and on[-7, -2, -9](the answer is -9). Change one sign and say which line you changed. - Count with a dictionary. Change the
bananaloop to count the letters of"mississippi". First work out the counts by hand (m, i, s, p), then run it. Then write a recursivetotal(items)that returns 0 for an empty list and otherwiseitems[0] + total(items[1:]), and check it gives 23 on[3, 1, 4, 1, 5, 9].
Go deeper
- The Python Tutorial, official documentation
- Python Tutor: paste code and step through it one line at a time
- Think Python, 3rd edition, by Allen Downey (free online)
- The Usenet post of 20 February 1991 announcing Python to alt.sources
Related
- Everything Is a Number (bits & bytes): values are bits in memory, so a name only finds a place.
- How Code Becomes Execution (compilers, stack & heap): code is steps run in order, and the call stack holds waiting calls.
- Complexity & Big-O: the next lesson, which counts the steps of loops like these.
- Arrays & Strings: lists and strings put to work.
- Hashing: why a dictionary lookup takes about one step.
- Recursion & Dynamic Programming: recursion in full, and the saved-answers table.
- Clinic #05: Two Sum: Two Sum worked in full.
- Foundations #02: Recursion → Memo → Table (DP ka engine): the Hinglish twin on recursion and saved answers.
Retrieval practice
8 questions. Answer each one before you open it.
What is the difference between = and == in Python?
A single = stores the value on its right under the name on its left. A double == asks whether two values are equal and gives True or False. Writing = where you meant == changes your data instead of asking a question.
A list has 8 values. Which indexes exist, and what is nums[-1]?
Indexes 0 to 7 exist, because counting starts at 0 and the last index is the length minus 1. nums[-1] is the same value as nums[7], the last one. nums[8] raises an IndexError.
How do you read a for loop without running it?
Write one line per value the loop takes, and under it the new value of each variable the body changes. For total = total + x over 3, 1, 4, you write 0 + 3 = 3, then 3 + 1 = 4, then 4 + 4 = 8. The unindented line after the loop runs once, at the end.
Why does count.get(ch, 0) + 1 work for a letter seen for the first time?
.get(ch, 0) returns the second value, 0, when the key is missing. So the first time a letter appears it stores 0 + 1 = 1. Later it finds the stored count and adds 1 to it. A plain count[ch] on a missing key raises a KeyError.
What does a function do when it reaches return?
It stops at once and hands one value back to the line that called it. If it never reaches a return, it hands back None. That is why a forgotten return shows up as None in the next line.
What two parts must a recursive function have, and what happens without the first?
It needs a base case, an input where it answers directly without calling itself, and a call on a smaller input that moves toward the base case. Without a base case the calls never stop, and Python raises RecursionError after 1,000 nested calls by default.
Why does fib(30) make 2,692,537 calls, and how does a dictionary fix it?
Each call makes two more calls, so the same fib(k) is worked out again and again, and calls(n) = calls(n − 1) + calls(n − 2) + 1. Saving each answer in a dictionary means each value is worked out once, so 2 × 30 − 1 = 59 calls.
In Two Sum, why is the dictionary filled after the check and not before?
The partner must be a different index. If x were stored first, then for a target of 6 and a value of 3, the lookup for the partner 3 would find the value itself and return the same index twice. Checking first, then storing, means only earlier values can be partners.
