CSSE1001 — Week 5 Notes
Comprehensions
Lecture 5B. See csse1001 for course logistics and python-comprehensions for the full reference on comprehension syntax.
Outline
- List comprehensions
- Dictionary comprehensions
- Nested comprehensions
- Two worked exercises:
disassembleandmore_capitals allandany- Filtering, and the general pattern
List comprehension
Mathematics builds sets and sums this way:
\[ \{k^2 : k \in \{0, 1, 2, 3\}\} = \{0, 1, 4, 9\} \qquad \sum_{k \in \{0,1,2,3\}} k^2 = 0^2+1^2+2^2+3^2 \]
Python mirrors this directly:
>>> [k**2 for k in range(4)]
[0, 1, 4, 9]
>>> sum(k**2 for k in range(4))
14
Dictionary comprehension
>>> {x: f"value is {x}" for x in range(3)}
{0: 'value is 0', 1: 'value is 1', 2: 'value is 2'}
>>> {x: 0 for x in "ABC"} # useful for assigning default values
{'A': 0, 'B': 0, 'C': 0}
>>> cs = "hello world"
>>> {x: cs.count(x) for x in cs}
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
Nested comprehensions
Multiple for clauses can appear in one comprehension — order matters:
>>> [(a, x) for a in "ABC" for x in range(2)]
[('A', 0), ('A', 1), ('B', 0), ('B', 1), ('C', 0), ('C', 1)]
>>> [(a, x) for x in range(2) for a in "ABC"]
[('A', 0), ('B', 0), ('C', 0), ('A', 1), ('B', 1), ('C', 1)]
Implementing [(a, x) for a in "ABC" for x in range(2)] with a for-loop:
>>> xs = []
>>> for a in "ABC":
... for x in range(2):
... xs.append((a, x))
Reading the two side by side is what makes the order rule obvious — and it explains why swapping the two for clauses swaps which loop is on the outside, and therefore changes the order of the result:
Figure 1: The same computation written both ways, piece by piece. Colour keys the boxed code: magenta the output expression, blue the outer generator clause, purple the inner one. The two italic sentences are annotations, not entries in that colour key. The for clauses keep their order, but the output expression jumps from the innermost loop body to the front.
Exercise: disassemble a string
def disassemble(cs: str) -> list[str]:
""" Returns a list of characters comprising cs, maintaining order.
>>> disassemble("")
[]
>>> disassemble("abcdef")
['a', 'b', 'c', 'd', 'e', 'f']
"""
With a for-loop:
>>> def disassemble(xs: str) -> list[str]:
... ans = []
... for x in xs:
... ans.append(x)
... return ans
With a list comprehension the whole body collapses to one line:
>>> def disassemble(xs: str) -> list[str]:
... return [x for x in xs]
>>> disassemble("abcdef")
['a', 'b', 'c', 'd', 'e', 'f']
The accumulator (ans = []), the loop, the append and the return of the four-line version all fold into the single comprehension.
return [c for c in cs]
Exercise: more capitals than lower-case
Check if a string has (strictly) more capitals than lower-case letters, ignoring all other characters:
def more_capitals(cs: str) -> bool:
"""
>>> more_capitals("aAbBcCdD")
False
>>> more_capitals("CSSE 1001")
True
>>> more_capitals("")
False
"""
A useful “hack”: the integer value of True and False is 1 and 0 respectively, so sum(...) over a sequence of booleans counts how many are True:
>>> True + True + False
2
return (sum('A' <= c <= 'Z' for c in cs)
> sum('a' <= c <= 'z' for c in cs))
Exercise: all
Check if every element of a list is truthy:
def all(xs: list) -> bool:
"""
>>> all([1, 2, 3])
True
>>> all(["a", "", "c"])
False
>>> all([])
True
"""
return len(xs) == sum(bool(x) for x in xs)
Exercise: any
Check if any element of a list is truthy:
def any(xs: list) -> bool:
"""
>>> any([0, 0, 0])
False
>>> any(["a", "", "c"])
True
>>> any([])
False
"""
return sum(bool(x) for x in xs) > 0
Both are already included in base Python — no library call needed — and they are useful:
>>> xs = "HELLO WORLD"
>>> all(['A' <= x <= 'Z' for x in xs]) # is every letter a capital?
False # (space is not a capital)
>>> any(['A' <= x <= 'Z' for x in xs]) # is any letter a capital?
True
Defining your own all/any as the two exercises above do shadows the built-ins for the rest of that scope — fine as an exercise in reimplementing them, a bug anywhere else.
Filtering
Comprehension elements may be filtered with a trailing if. E.g. the numbers less than 100 divisible by both 3 and 7:
>>> [x for x in range(101) if not (x % 3) and not (x % 7)]
[0, 21, 42, 63, 84]
range(101) includes 100. It makes no difference here — 100 is divisible by neither 3 nor 7 — but range(100) is what “less than 100” asks for.
The general pattern
[x for x in xs if P(x)]
[x for x in xs for y in ys if P(x, y)]
[x for x in xs for y in ys for z in zs if P(x, y, z)]
...
where P is some predicate.
Summary
Comprehensions are a rapid way of forming lists and dictionaries that would otherwise require an accumulator for-loop.
Next: week-five-exercises (Lecture 5C). See python-comprehensions for the syntax reference and python-for-loops for the accumulator forms comprehensions shortcut.
For-Loops
Lecture 5A. See csse1001 for course logistics and python-for-loops for the full reference on for-loop syntax, ranges, and enumerate.
Outline
- For-loops: definition and syntax
- String iteration, character by character; nesting for-loops
- The accumulator pattern
- For-loops vs. while-loops — which can replace which
- List looping, index by index; out-of-place vs. in-place
range(iterating through numbers) andenumerate(iterating with index)- Dictionary looping, key by key
Definitions
Loop — a control structure that repeats code that belongs to it.
For-loop — a control structure that, given a group, repeats code for every member of that group, in order.
for <name> in <iterator>:
<code>
String iteration (character by character)
A for-loop iterates through a string’s characters, in order:
>>> for x in "abcd":
... print(x)
a
b
c
d
>>> x
'd'
The looping name (x) retains its final value after the loop exits.
Nesting for-loops
>>> (digits, alphas) = ("012", "xy")
>>> for d in digits:
... for a in alphas:
... print(d + a)
0x
0y
1x
1y
2x
2y
Python disallows empty for-loop bodies — use pass (the empty instruction, which has no effect) as a placeholder:
>>> for d in digits:
... for a in alphas:
... pass
... print(d + a)
0y
1y
2y
Again, the names used to iterate through an iterator retain their values after the for-loop exits — by the time the outer loop’s print runs, the inner loop has already finished, leaving a at its last value ('y') each time.
Pulling print out of both loops leaves it running exactly once, on whatever d and a were left holding:
>>> (digits, alphas) = ("012", "xy")
>>> for d in digits:
... for a in alphas:
... pass
... print(d + a)
2y
So the same two loops give six lines, three lines or one line depending only on where print is indented.
Figure 2: Where the print statement is indented decides how many times it runs. The tree is the order the two nested loops visit their six (d, a) combinations, left to right. The three variants (6 lines, then 3, then 1) are keyed by the box around each printed value — none, purple, blue — and by nothing else: the purple traversal-order label beneath the tree is an annotation, not a fourth entry in that key.
The accumulator pattern
An accumulator is a variable a loop uses to build up an aggregate value:
>>> acc = ""
>>> for x in "abcd":
... acc = acc + x
... print(acc)
a
ab
abc
abcd
Building it in reverse order just by swapping the order of concatenation:
>>> acc = ""
>>> for x in "abcd":
... acc = x + acc
... print(acc)
a
ba
cba
dcba
The loop visits 'a', 'b', 'c', 'd' in the same order both times — only the side the new character is joined on changes, and that alone reverses the result:
Figure 3: Why acc = acc + x builds abcd and acc = x + acc builds dcba. The top row, marked before the loop, is the empty accumulator each snippet sets up on its first line — not a pass, and never printed; each of the four rows below it is one pass, and the magenta cell is the character just added. Those four rows per column are exactly the printed output of the two loops above.
For-loops vs. while-loops
Can every for-loop be rewritten with only while-loops? Yes:
>>> for x in xs:
... ... # do something with x
is code-equivalent to:
>>> k = 0
>>> while k < len(xs):
... ... # do something with xs[k]
... k += 1
Can every while-loop be rewritten with only for-loops? No — consider how many times you’d need to repeat asking a user for correct input (not known in advance). That is exactly the validation loop from 2025-08-18-while-loops: the trip count is not known until the user cooperates, so there is no group to iterate over.
Technical caveat: a for-loop can be tricked into looping forever in Python, by giving it an iterator that never exhausts. And if you dig deep enough, Python itself used a while-loop to build that iterator in the first place.
Exercise: removing characters
def remove(c: str, cs: str) -> str:
""" Return the string with all instances of c removed from cs.
Precondition: len(c) == 1
>>> remove('b', "bluey")
'luey'
>>> remove('b', "Bluey")
'Bluey'
>>> remove('b', "chilli")
'chilli'
>>> remove('b', "")
''
"""
The shape is the accumulator pattern: accumulate into acc, skipping the character to be removed. The loop variable needs its own name (x), compared against the parameter c. Reusing c as the loop variable would shadow the parameter it is supposed to be compared against.
Fill in the blank to complete remove:
acc = ""
for x in cs:
if x != c:
acc += x
return acc
List looping (index by index)
A for-loop also iterates directly through a list’s elements. This example uses no index at all — indices arrive later, with range and enumerate.
>>> xs = ['a', 2, 'c', 4, 'e']
>>> for x in xs:
... print(x)
a
2
c
4
e
Exercise: unique elements
def make_unique(xs: list[int]) -> list[int]:
""" Returns the UNIQUE elements of xs.
>>> make_unique([1, 2, 3, 4])
[1, 2, 3, 4]
>>> make_unique([1, 2, 2, 2, 3, 1, 4, -3])
[1, 2, 3, 4, -3]
"""
acc = []
for x in xs:
if x not in acc:
acc.append(x)
return acc
This is an out-of-place computation — the original list xs is not modified. An in-place change would instead modify xs directly; those are covered later, in the object-oriented part of the course.
Ranges (iterating through numbers)
range builds an iterator of numbers, with the general form range([start], stop[, step]) (square brackets denote optional arguments) — similar to list slicing:
>>> range(10)
range(0, 10)
>>> type(range(10))
<class 'range'>
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(2, 7))
[2, 3, 4, 5, 6]
>>> list(range(2, 7, 3))
[2, 5]
>>> list(range(2, 7, -1))
[]
>>> list(range(7, 2, -1))
[7, 6, 5, 4, 3]
The rule for reading the last four follows the slicing analogy: the walk starts at start, hops by step, and yields every value it lands on that is still short of stop in the direction it is travelling. So stop is never produced, and start is produced only when the walk produces anything at all: range(2, 7, -1) is empty because a negative step walks down from 2, away from 7, and 2 is already past 7 going that way, so not even start comes out. See python-for-loops for a diagram of those four.
range is commonly used to walk through a list by index:
>>> xs = [11, 22, 33, 44]
>>> for k in range(len(xs)):
... ... # code involving xs[k]
Enumerate (iterating with index)
enumerate simplifies the index-and-value pattern above. Roughly:
enumerate([x0, ..., xn]) == [(0, x0), ..., (n, xn)]
(this isn’t the full story — enumerate actually returns an iterable, not a list — but the pairs it produces work the same way):
>>> xs = [1, 2, 3, 4]
>>> for k, xk in enumerate(xs):
... ... # code involving k and xk == xs[k]
Each (k, xk) pair is a tuple, an immutable list (see python-lists):
>>> for k, x in enumerate(["Scientia", "ac", "Labore"]):
... print(k, x)
0 Scientia
1 ac
2 Labore
(“Scientia ac Labore” is UQ’s motto — “by means of knowledge and hard work”.)
Dictionary looping (key by key)
A for-loop iterates through a dictionary’s keys (see python-dictionaries) — not its values, and not its key/value pairs. To reach a value you index the dictionary with the key the loop hands you:
>>> for key in table: # for loop over keys
... value = table[key]
>>> h = {"red": 1, "blue": 2, "green": 3}
>>> for key in h:
... print(key)
red
blue
green
>>> for key in h:
... print(h[key])
1
2
3
Exercise: character index
Write a function that maps each character of a string to the list of indices at which it occurs:
def char_index(xs: str) -> dict[str, list[int]]:
""" Return a dictionary mapping the characters (length one
substrings) of <xs> to the list of indices at which they occur.
>>> char_index("")
{}
>>> char_index("aaAbbB")
{'a': [0, 1], 'A': [2], 'b': [3, 4], 'B': [5]}
"""
acc = {}
for k, x in enumerate(xs):
if x in acc:
acc[x].append(k)
else:
acc[x] = [k]
return acc
Summary
For-loops let us iterate through anything iterable. Strictly speaking they’re not necessary (a while-loop, or copy-pasting code k times, can always do the same job) but they’re used often enough to merit their own dedicated syntax.
Next: 2025-08-25-comprehensions (Lecture 5B) — a rapid way of building lists and dictionaries that would otherwise need an accumulator for-loop.
Week 5 Exercises — For-Loop Practice
Practice exercises for week 5 (Lecture 5C, “For Loop Practice”), following on from 2025-08-25-for-loops and 2025-08-25-comprehensions. See python-for-loops and python-comprehensions for the reference material needed to solve these.
Q1–Q6 are the week 5 set. Q7–Q11 are the week 4 exercises, from 2025-08-18-while-loops (Lecture 4A) and 2025-08-18-non-primitive-data (Lecture 4B). Q7 is also worked three ways in 2025-08-18-non-primitive-data; it is repeated here because it is the same shape as the rest. Q8–Q11 are worked here, as is the week 4 Caesar cipher (Q3). Every one is a loop over a list, a dictionary or a counter, so they belong in the same practice set. See python-lists, python-dictionaries and python-while-loops for the reference material those need.
On the HTML site, fill in each blank with your answer, then click Run Code to check it. In the PDF, the Working callout is shown as a static answer key instead (interactive checking needs a browser).
The figures use the palette recorded in csse1001-diagram-notation.
Q1 — Capitalize a string
def capitalize(cs: str) -> str:
""" Capitalize every alphabet letter of a string.
>>> capitalize("boom goes the dynamite!")
'BOOM GOES THE DYNAMITE!'
>>> capitalize("123")
'123'
"""
acc += chr(ord('A') + ord(c) - ord('a'))
Shifting a lower-case letter up to its capital by the fixed gap between 'A' and 'a' in the character encoding.
Q2 — Matrix transpose
def transpose(xss: list[list[int]]) -> list[list[int]]:
""" Return the transpose of xss (rows and columns swapped).
Precondition: xss is square, i.e. len(xss) == len(xss[0]) == ...
>>> transpose([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
[[1, 4, 7], [2, 5, 8], [3, 6, 9]]
>>> transpose([[1]])
[[1]]
"""
Figure 4: Q2 on a \(3\times3\) matrix. A matrix can be represented by a list-of-lists in Python, and indexing it takes two steps — xss[1][-1] is 6, while xss[1,-1] raises TypeError: list indices must be integers or slices, not tuple. Row \(k\) of the result is column \(k\) of the original, which is the whole of the answer. Magenta marks column 1 of xss and the row of the result it becomes.
row = [xs[k] for xs in xss]
Row k of the transpose is column k of the original — the k-th element of every row xs in xss, which is what Figure 4 draws.
Written out with two-step indexing instead of a comprehension, the same row is [xss[i][k] for i in range(len(xss))]. The comprehension form is shorter because xs is xss[i].
Q3 — Caesar cipher
A Caesar cipher shifts each letter a fixed number of places down the alphabet (wrapping around) to encrypt; shifting by the negative amount decrypts it again.
def caesar_cipher(cs: str, shift: int) -> str:
""" Return a string where each character of <cs> has been shifted
by <shift> according to the Caesar cipher.
>>> caesar_cipher("HELLO", 3)
'KHOOR'
>>> caesar_cipher("KHOOR", -3)
'HELLO'
>>> caesar_cipher("abc xyz", 2)
'cde zab'
>>> caesar_cipher("cde zab", -2)
'abc xyz'
"""
The Caesar cipher exercise in 2025-08-18-non-primitive-data asks for separate
encrypt_caeseranddecrypt_caeserfunctions. Same idea here, with a single shift parameter instead of two functions:decrypt_caeser(ct, s)iscaesar_cipher(ct, -s).
acc += chr((ord(c) - ord('a') + shift) % 26 + ord('a'))
% 26 wraps the shift around the alphabet in both directions (including for negative shifts, since Python’s % always returns a non-negative result for a positive divisor).
Q4 — Combine two dictionaries
def combine(d1: dict[int, list[int]], d2: dict[int, list[int]]) -> dict[int, int]:
""" Return the dictionary where each key is a key that is in both
d1 and d2. The value for each key is the sum of all the integers
associated with that key in d1 and d2.
>>> combine({1: [2], 4: [5, 6]}, {4: [8]})
{4: 19}
"""
acc[key] = sum(d1[key]) + sum(d2[key])
The if key in d2 guard is what keeps d2[key] from raising a KeyError. Bare indexing of a missing key raises an error such as KeyError: 'green'. The method alternative, h.get(key), is safer because no error is thrown: it returns None instead.
Q5 — Reverse lookup
def reverse_lookup(d: dict, item) -> list:
""" Returns all keys of <d> such that d[key] == item.
Precondition: the items of <d> are immutable.
>>> reverse_lookup({1: 'bluey', 19: 'chilli', -31: 'bluey'}, 'bluey')
[1, -31]
>>> reverse_lookup({1: 'bluey', 19: 'chilli', -31: 'bluey'}, 'muffin')
[]
"""
A dictionary gives every key one value, but nothing stops two keys sharing a value — which is the only reason this function returns a list. Figure 5 under Q6 draws that.
if d[k] == item:
In CSSE1001 a dictionary is treated as having no ordering, because the keys can be of mixed type. The expected answer [1, -31] nevertheless comes out in the order the keys were written, and [-31, 1] would fail the check above.
A dict iterates in insertion order from Python 3.7 onward. The habit that works either way is not to depend on the order — compare as a set, or sorted(...), when the order is not part of the specification.
Q6 — Invert a dictionary
def invert(d: dict) -> dict:
""" Return the inverted version of d (values become keys, mapping
to a list of the original keys that shared that value).
>>> invert({1: 10, 2: 10})
{10: [1, 2]}
"""
Figure 5: Q5 and Q6 are one picture read in two directions, drawn on Q5’s dictionary. A dictionary is a store of tuple(key, value) pairings found by a hash function. Each arrow is one pairing, which can also be written as a maplet such as \(\texttt{h} \mapsto 1\). A dict gives every key exactly one value, so several keys can land on the same value — 1 and -31 both map to 'bluey'. reverse_lookup follows those arrows backwards for one chosen value; invert reverses all of them at once, which is exactly why the inverted value has to be a list: reversing a many-to-one map gives a one-to-many map. The key order shown is the literal order Q5 writes the dictionary in; nothing should be read into it.
acc[val] = [key]
A one-element list, not the bare key — the if branch above then has something to .append to on the second key that shares this value. Getting this wrong is the usual way Q6 fails: acc[val] = key works for {1: 10} and breaks the moment two keys collide, which is the only interesting case.
This is the same shape as the way of avoiding a KeyError without methods:
if key in table:
table[key] += 1
else:
table[key] = 0
Q6 is the same test with a list in place of a counter. That else branch initialises a new key to 0 rather than 1, which would leave every count one low.
Carry-over: the week-4 exercises
Everything from here on comes from week 4: while-loops (2025-08-18-while-loops, Lecture 4A) and lists and dictionaries (2025-08-18-non-primitive-data, Lecture 4B). Q7 is also worked in 2025-08-18-non-primitive-data. Q8–Q11 are stated in those two notes and worked here.
Q7 — Count occurrences
def count(xs: list[int], ys: list[int]) -> int:
""" Return the number of times members of ys are in xs.
>>> count([1, 2], [1, 2, 3, 4])
2
>>> count([1, 2], [1, 2, 2, 2, 3, 1, 4])
5
"""
Read the specification carefully: the walk is over ys, and xs is only ever asked does it contain this. That is why the second example answers 5 and not 2 — five of the seven members of ys are in xs, counting repeats.
if y in xs:
in is list membership. The whole function can be written three ways.
The while-loop version, walking ys by index:
def count(xs: list[int], ys: list[int]) -> int:
ans, k = 0, 0
while k < len(ys):
y = ys[k]
k += 1
if y in xs:
ans += 1
return ans
The for-loop version. It is certainly better to use a for-loop in this situation.
def count(xs: list[int], ys: list[int]) -> int:
ans = 0
for y in ys:
if y in xs:
ans += 1
return ans
The one-line version.
def count(xs: list[int], ys: list[int]) -> int:
return sum(y in xs for y in ys)
That last one leans on True counting as 1 under sum, and on the generator-expression syntax of 2025-08-25-comprehensions.
Q8 — Rotate a list
def rotate(xs: list, k: int) -> list:
""" Return xs rotated by k.
>>> rotate([0, 1, 2, 3, 4, 5], 2)
[2, 3, 4, 5, 0, 1]
>>> rotate([0, 1, 2, 3, 4, 5], 0)
[0, 1, 2, 3, 4, 5]
"""
The hint is slicing, as in xs[3:6], xs[::2] and xs[7:2:-2].
Figure 6: The rotate exercise solved by slicing. Along the top are the list, the rotation amount and the answer; rotation is defined by that one example and nothing else. Below, the answer: xs[:k] and xs[k:] are the two blocks the list splits into, and rotating is writing them in the other order. Nothing moves within either block, which is why one concatenation of two slices, xs[k:] + xs[:k], is the whole function.
return xs[k:] + xs[:k]
Two slices concatenated, as in Figure 6. The slice bounds need no guarding for k = 0 (xs[0:] is all of it, xs[:0] is empty) and none for k = len(xs) (the other way round), so both ends of the range come out right for free.
The exercise defines rotation by a single example, which leaves two cases unsettled:
klarger than the list.rotate([0, 1, 2], 5)returns[0, 1, 2]unchanged, becausexs[5:]is empty. If a rotation by 5 of a 3-element list should mean a rotation by 2, open withk = k % len(xs). The single example never leaves the range, so it does not say which is wanted.- Negative
k.rotate([0, 1, 2, 3, 4, 5], -1)gives[5, 0, 1, 2, 3, 4]— a rotation the other way. That falls out of Python’s negative-index rule rather than out of any decision, and the example does not say whether it is wanted either.
An index-based alternative, if you want it as a for-loop rather than a slice:
def rotate(xs: list, k: int) -> list:
return [xs[(i + k) % len(xs)] for i in range(len(xs))]
This one does handle k beyond the length, because the % is applied per element.
Q9 — Roll until a six
def roll_until_six() -> int:
""" Print the result of each roll of a six-sided die until a six
is rolled. Return the number of rolls required.
"""
Random number generation is not built in and must be imported:
>>> from random import randint
>>> randint(1, 6) # chosen uniformly over the interval
2
if roll == 6:
The loop is while True for the same reason as the guess-the-number game in 2025-08-18-while-loops: the value the condition needs to test does not exist until the body has run, so there is nothing to put at the top of the loop. The exit is a return, which leaves the function and so the loop outright (break is for the case where there is nothing to hand back).
Because randint is re-rolled every pass, this loop has no bound on how long it runs — only a probability of stopping. That is repeating possibly indefinitely, which is what a while-loop is for, and it is why this cannot be a for-loop.
The rigged die in the cell above is a testing device: rebinding the name randint after the function is defined makes the function pick up the replacement, because Python resolves a global name at call time and not at definition time. Delete those two assignments and the function rolls for real.
Q10 — Accumulate rolls until a threshold
def rolls_to_reach(threshold: int) -> int:
""" Roll a six-sided die, accumulating the results, until the running
total meets or passes <threshold>. Return the number of rolls required.
"""
Q9’s stopping condition looks at the latest roll. This one looks at an accumulator over all of them — the x = x + 1 pattern, which the Python assignment operators let you write as x += 1.
while total < threshold:
Unlike Q9 this loop has a real condition to put at the top, so it needs no while True and no break: total is a genuine accumulator, and the test “have we got there yet” can be asked before the first roll. At the boundary, with threshold = 0, the body never runs at all and the answer is 0 rolls, the same as a while False loop.
The specification says met/passed, so the test must be strict (total < threshold), not total <= threshold: the loop has to stop the moment total reaches the threshold exactly. With the rigged die above the sixth roll takes the total to exactly 20, so a <= here would answer 7 rather than 6 — the boundary is not academic.
Q11 — Addition and multiplication from succ and pred
Two building blocks are given, and the arithmetic has to be built from nothing else:
def succ(x: int) -> int:
return x+1
def pred(x: int) -> int:
return x-1
Develop functions for adding and multiplying positive integers together restricting ourselves to exactly two arithmetic operations:
succ(adding one) andpred(subtract one).
Figure 7: Why the add loop of Q11 is correct and why it stops, traced on add(3, 4). Each pass moves one unit from b across to a, so the total width of the row — the quantity a + b — is the same on every line: it starts at \(3+4\) and ends at \(7+0\), which is why a holds the answer at the moment b reaches 0. The same reading gives termination, since b strictly decreases and cannot go below 0.
total = add(total, a)
add is succ applied b times, and multiply is add applied b times: each function is one loop that walks b down to zero with pred while doing the previous operation once per step. That layering is the point of the exercise — multiplication is repeated addition in the same way addition is repeated succession.
def add(a: int, b: int) -> int:
while b > 0:
a = succ(a)
b = pred(b)
return a
def multiply(a: int, b: int) -> int:
total = 0
while b > 0:
total = add(total, a)
b = pred(b)
return total
Figure 7 is the argument that add is right: a + b is unchanged by the body, so when the loop ends with b == 0 the surviving a is the original a + b. The same trace argues termination — b strictly decreases every pass, so a non-negative b must reach 0.
Both functions read b down to zero and never test a, so the stated precondition matters on one side only: b must be non-negative or the loop never starts and you get a (for add) or 0 (for multiply) back. The exercise says positive integers, so nothing outside that is specified.
Both functions are accumulators driven by a while-loop, which is what makes this a while-loop exercise rather than an arithmetic one.
Reference material
CSSE1001 Diagram Notation
This note records the drawing conventions CSSE1001 actually uses, inferred from its own lecture slides. It is the reference that later diagrams in this course should be checked against.
There is no written style or notation standard anywhere in the CSSE1001 materials. The course profile lists no prescribed textbook and no drawing guide; the “Learning resources” section points only to the UQ Library, Blackboard and Ed Lessons. Every convention below is inferred from the drawings themselves, not quoted from a rule.
The three exceptions — places where the slides state a rule in words rather than merely demonstrate one — are the naming conventions (see Naming and capitalisation) and the one figure-source note in 12b. Everything else is observation.
How to read the citations
Decks are cited by their lecture code and PDF page number, e.g. 10a p7 = the UML deck, seventh page of the PDF.
Do not cite the printed footer numbers. They are unreliable: 09a runs 1/14 … 4/39, 5/39, 6/14 … 15/14, 16/15 and then ends on a page footed 14/14 that is actually PDF page 17. Several decks have footer totals that disagree with their own length (11a’s last page reads 14/13). PDF page index is the only stable address.
Colours were sampled from the rendered pages, quantised to 16 levels per channel, so hex values are accurate to roughly ±8 per channel.
What I sampled
248 pages read as images, out of 726 across 25 decks — 17 of the 25 decks. Full text was extracted from all 25 decks plus the course profile, and every deck was scanned for embedded raster images, so the unread decks were checked for figures even where I did not read them.
| Deck | Pages read |
|---|---|
| 01a history-of-computing | 22–33 |
| 02a python-memory-model | 4–28 |
| 03a functions | 23–28 |
| 03b sequence-selection-and-iteration | 2–19 |
| 04b non-primitive-data | 2–17 |
| 07a exceptions | 14–21 |
| 07b scope | 5–19 |
| 07c object-oriented-programming | 2–19 |
| 08a dunder-methods | 2–5 |
| 08b representation-invariants | 5–14 |
| 09a composition | 1–17 (all) |
| 09b inheritance | 1–19 (all) |
| 10a uml | 1–14 (all) |
| 10b advanced-inheritance | 1–20 |
| 11a model-view-controller | 1–14 (all) |
| 12a recursion | 2–15 |
| 12b complexity-and-sorting | 2–19 |
Not read as images: 00-welcome, 01b python-as-a-calculator, 02b primitive-data, 04a while-loops, 05a for-loops, 05b comprehensions, 06a string-methods, 06b file-io. An image-extraction scan across all decks found zero embedded raster images in seven of those eight (00-welcome has six photo pages), and they are typeset in the same LaTeX Beamer template as the decks I did sample. So the risk that they hide an unseen diagram idiom is low but not zero — the eight decks above are the blind spot in this note.
The two slide families
Almost every visual inconsistency in this course traces back to one fact: the decks come from two different production pipelines, and many decks mix both on adjacent pages.
LaTeX Beamer family — serif body text (Computer Modern), ruled code listings with line numbers, coloured named block headings, no raster images. Covers 01b, 02a, 02b, 03a, 03b, 04a, 04b, 05a, 05b, 06a, 06b, and most of 07a/07b/12a/12b.
PowerPoint family — sans-serif labels, filled colour boxes, drop shadows, stock photography, dark-theme code screenshots. Every deck carrying Based on slides from Dr. Azadeh Ghari-Neiat on its title page (07a, 07b, 07c, 08a, 08b, 09a, 09b, 10a, 10b, 11a) contains PowerPoint-family pages.
Consistency: this split holds across the whole semester and is the single most useful thing to know before drawing anything for this course.
Colour palette
These five colours carry meaning and recur across many decks. Everything else is decorative.
| Colour | Sampled | Means | Evidence |
|---|---|---|---|
| Dark blue | #3030B0 |
Slide title | 10a p4, p7, p10; 09a p12; 10b p10, p19 |
| Magenta | #E00080 |
Defined term, emphasis, the answer | 10a p4; 02a p6; 12a p2 |
| Purple | #92278F |
Named block heading; margin annotation | 03b p4; 12b p19; 09a p12; 10b p13 |
| Green | #109050 (LaTeX) / #00B050 (PPT) |
A prompt to the student | 02a p5; 03b p11; 10a p12; 11a p8 |
| Red | #F00000 |
Warning / failure path | 12a p10; 07b p13; 04b p14 |
Purple #7030A0 is a different purple. It is used only for the UML legend boxes (10a p7, p8, p10, p11) and for the Warning heading in 07b p6. Do not conflate it with the block-heading purple.
Consistency: the blue/magenta/purple/green assignments hold from week 2 (02a) to week 12 (12b). Red is the least consistent — see Inconsistencies.
Named block headings
LaTeX-family slides open a block with a coloured heading on its own line, no box and no rule.
- Green — a prompt the student is meant to act on:
Question(02a p5, 12b p3, p9, p12),Exercise(03b p11, p14; 12b p5, p8, p11, p15; 09b p17; 10a p12; 11a p8),Example(02a p22, p24, p25),Task(07b p17). - Magenta italic — the resolution:
Answer(02a p6, p7, p8, p9, p23; 12b p18). - Purple — a formal or named block:
Definition (…)(03b p4, p6, p7, p12; 04b p3; 07c p5; 12b p19),Proposition(12a p13),Base Case/Induction Hypothesis(12a p14),Observe(03b p10),Summary/Next(02a p28, 07a p21, 07b p19),Constants(07b p5), and named algorithmsInsertion Sort/Bubble Sort/Merge Sort/Quick Sort(12b p3, p6, p9, p12, p16).
Definition blocks are parenthesised with the term being defined: Definition (Boolean domain), Definition (Predicate), Definition (List), Definition (Complexity).
Consistency: green/magenta/purple hold across at least five decks spanning weeks 2–12. The Warning heading is the exception.
Section divider slides
A section break is a slide bearing one large magenta italic serif word, left-of-centre and high on the page, with a short parenthetical gloss beneath it in small black roman type.
Variables— (Named memory locations.) — 02a p14Sequencing— (Order of instructions matters.) — 02a p21Selection— (Controlling program flow.) — 03b p2Lists— (Mutable Ordered Collections.) — 04b p2Memes— (Recursions through meme examples.) — 12a p3
When a deck runs a numbered series of dividers, they take Roman numerals with a colon, and the series continues across decks:
I: Structure— (Holding named attributes.) — 07c p8II: Methods— (Object scoped functions.) — 07c p15III: Magic— (Overloading built-in functions.) — 08a p5
Consistency: strong — six plain dividers across four decks, plus a three-part numbered series spanning two decks. One divider (08b p11, Exercise) carries no gloss.
Code listings
Code is by far the most frequently drawn thing in this course, and its presentation is a notation in its own right.
Ruled block. A listing is bounded by a horizontal rule above and below, full text width, with no vertical rules and no background fill. Line numbers run in tiny grey type in the left margin. Code is monospace with visible letter-spacing.
REPL vs. file. The two are distinguished by prompts, not by styling:
- A REPL transcript uses a magenta
>>>prompt for the first line of an input and a magenta...for continuation lines; output follows on its own line with no prompt (02a p13, p15–p20; 03b p5, p8, p13, p15–p18; 04b p4–p13; 07b p5–p16; 10b p9, p11, p15, p18). - A file or definition is shown with line numbers but no prompts at all (04b p15, p16, p17; 08b p6, p9, p13, p14; 09a p10–p14).
Colour inside code. Black is the default. Magenta marks the token or line under discussion — class names being introduced (Battery, Camera, Motor, 09a p10, p11), the lines inherited or overridden (10b p10, p13, p17), the assert keyword (08b p6, p9), the constant being referenced (08b p13, p14). Boolean operators are coloured by identity: and in cyan, or in green, held consistently through 03b p9, p10, p11, p14.
Vertical ellipsis. Elided code is a centred ⋮ on its own line (03a p23) or three stacked full stops (07a p15).
Placeholder metasyntax. Things the student must substitute are written in angle brackets in monospace: <code> and ExceptionName_k (07a p15, p16), <object_variable>.<method>(<parameters>) (07c p16), <statement that should be true> (08b p5). Consistency: three decks.
Annotating code
This is the course’s real “diagram” vocabulary — it annotates listings far more often than it draws figures.
Right-margin note. A short purple italic serif phrase, right-aligned, on the same line as the code it comments on. Sampled #92278F in both 09a p12 and 10b p13 — identical colour, three decks apart. (Measured by histogram at 300 dpi. The neighbouring aside on 09a p13 is #92268F, one unit off in green and blue — the same ink to the eye, but the two pages are not bit-identical.)
Examples: inherit from A, override, extend from B from A, Super is B (10b p10, p13, p14, p17, p18); Drone has-a Battery (09a p12); this is the memory location where 42 is stored (02a p13); Note addition happened first (03b p5); ys is an alias of xs, Aliasing relationship broken! (04b p13); a ‘private’ variable, this is called a ‘getter’ (07c p19); unreachable if line 5 errors (07a p14).
Consistency: the strongest single convention in the course — present in 02a, 03b, 04b, 07a, 07b, 07c, 09a, 10b. Weeks 2 through 10.
Boxed token. A thin rectangle drawn around an identifier inside the listing, marking the thing being named. The box colour is not fixed: purple around Point() and self (07c p9, p16), magenta around raise ZeroDivisionError (07a p18), blue around Child and purple around Parent (09b p9). See Inconsistencies.
Brace grouping. A magenta right-brace } spanning consecutive lines, with a magenta italic label beside it — Attributes beside the two self.x = 0 / self.y = 0 lines (07c p9). Single instance.
Pointer arrow. A straight or gently curved arrow from an annotation to the code element it refers to. Magenta in 07c p12 and p16; orange in 09b p12 and p13; blue and purple in 09b p9.
Colour keying. Where an annotation has a coloured box and a coloured arrow and a coloured word in the caption, all three share one colour: on 09b p9 the blue box round Child, the blue arrow, and the word “Child” in the caption are all blue, and Parent is purple throughout. Two instances (09b p9, p12); treat as a good practice rather than a settled rule.
Focus markers. Small green right-pointing triangles in the far-left margin flag the lines the reader should look at (07b p7, p12). Two instances, one deck.
Scope boxes
The clearest original notation in the course, in 07b.
A rounded rectangle drawn over a span of code lines delimits a scope, and its colour names the scope kind:
- Purple outline, no fill — global scope; encloses the whole snippet (07b p7, p12).
- Blue outline, pale blue fill — local/function scope; encloses the
defbody only (07b p7, p9, p12).
Nesting is literal: on 07b p7 and p12 the blue local box sits inside the purple global box.
Each box is paired with a short horizontal arrow leading out to a colour-matched label — purple arrow to purple global variable, blue arrow to blue local variable (07b p7, p8, p9, p12).
Consistency: four pages of one deck, entirely self-consistent. Never reused elsewhere in the semester.
UML class diagrams
The formal UML vocabulary is taught in 10a and reused once in 10b p19.
Class box. A black-outlined rectangle in three compartments, separated by full-width horizontal rules: name (centred, serif) / attributes / methods (both left-aligned). 10a p6 states the rule in words and shows it twice.
Visibility prefixes. Stated explicitly on 10a p6: - private, + public, # protected. Applied consistently on 10a p7–p11: #name: str, -breed: str, +speak().
Attribute typing. name: type with a Python type — #age: int, -nationality: str, -pets: [] (10a p6, p9, p11). Methods show a return type only sometimes: +info(): str (10a p6) but bare +info() (10a p7–p11).
Empty compartments are kept. Cat on 10a p8–p11 keeps a visibly empty attributes compartment rather than collapsing to two compartments.
Single-compartment boxes are acceptable when only structure is being shown — 10a p4 and 10b p19 draw name-only boxes.
Relationship symbols
| Relationship | Symbol | Evidence |
|---|---|---|
| Inheritance | Solid line, solid filled triangular arrowhead, pointing up into the parent | 10a p4, p7–p11; 10b p19 |
| Association | Plain solid line, no head, optional verb label at one end | 10a p8 (drinks), p9 (Associated) |
| Composition | Solid line, filled diamond at the “whole” end | 10a p10 |
| Aggregation | Solid line, hollow (white-filled) diamond at the “whole” end | 10a p11 |
Standard UML draws generalisation as a hollow triangle. This course draws it solid filled, verified at 600 dpi on 10a p7 and again on 10b p19. Every inheritance arrow in the course is filled. If you conform to standard UML you will not match the slides; if you match the slides you will not match standard UML. Follow the course.
Line routing is orthogonal. All relationship lines use right-angle elbows, never diagonals (10a p8–p11). A parent with several children gets a single vertical stem down from the parent to a horizontal bus, with vertical drops to each child (10a p4, p7–p11; 10b p19).
Layout and flow. Parent above, children in a row beneath. A grandchild hangs directly below its own parent with its own vertical arrow (10b p19: C below B). Associated non-hierarchy classes sit to the side at the same height as the class they attach to (10a p9 Vet, p10 Heart, p11 Owner).
Multiplicity. Placed above the line, adjacent to the end it qualifies, in magenta — 1..* at both ends (10a p9), 1 and 1 (10a p10), 0..* (10a p11). 10a p9 gives the vocabulary in a legend box: 0..1 zero to one, n specific number, 0..* zero to many, 1..* one to many, m..n specific range.
Magenta marks the relationship being taught. On each of 10a p7–p11 the relationship introduced on that slide is drawn in magenta while previously-established structure reverts to black. On p7 the inheritance tree is magenta; by p8 it is black and the new association line is magenta. Consistency: holds on all five relationship slides — a deliberate, reusable device.
Legend box. A rounded rectangle with a purple #7030A0 outline, containing the relationship name in purple and the bare symbol drawn beneath it, parked in the top-left corner (10a p7 Inheritance, p8 Association, p10 Composition, p11 Aggregation). The multiplicity legend on 10a p9 uses the same box for a text list instead of a symbol.
Non-UML class and object diagrams
Before UML is taught in week 10, the course draws classes at least four other ways. These are not variants of one style — they are four unrelated idioms.
(a) Uniform blue hierarchy — flat steel-blue #4F81BD filled rectangles, white sans-serif labels, parent above and children in a row, joined by a #3D6696 orthogonal bracket with no arrowhead at all — a darker shade of the box fill, not black, though it reads as black at slide size. Photos of instances sit below each child. (09b p2, p3)
(b) Multi-colour hierarchy — parent box black with white text; each child a different Office-palette fill — and these are the stock Office 2007 accents exactly, which is why they recur: #C0504D brick red, #4BACC6 teal, #F79646 orange, #215968 dark teal, olive. Connectors are thin #4A7EBB straight lines — diagonal from the outer children, vertical from the one directly beneath — and each ends in its own arrowhead. On 09b p5 three arrowheads overlap on Animal’s bottom edge; at slide size they read as one, but there are three. (09b p4, p5, p6)
Black for the root holds in all three of these diagrams (Employee, Animal, Person). The child colours carry no meaning I can find — Dog stays teal on 09b p5 even though it is itself a parent.
(c) Attributes-over-methods box — the class name in purple bold sans-serif above two stacked magenta-outlined boxes: attributes on top, methods beneath, with a photo of an instance alongside. (07c p6, three times: Dog, Student, Smartphone)
(d) Attributes-left / methods-right — the class in a black-outlined box in the centre with its name in black and (class) beneath in magenta; a purple-outlined attributes box to the left and a magenta-outlined methods box to the right, each with a plain black label above it. Instances are photographs below, reached by straight black downward arrows with solid heads. (08a p2)
08a p2 draws class → instance as a downward arrow. Every inheritance arrow in the course points up to the parent. The two are never shown on the same page, so the contrast is safe — but keep it.
(e) Containment (“has-a”) boxes — composition is drawn as nesting, not as a line. A large steel-blue #4080B0 filled rectangle is the whole, labelled in large white text at its right edge (car, drone); a smaller brick-red #C05040 rounded rectangle sits inside it and is the part, labelled in white at its top with its methods listed beneath (engine / stop() / start()). (09a p6, p16)
Substitution is shown by stacking two such figures and joining them with a thick curved orange #F79646 arrow from the old configuration to the new (09a p16, “Hot-Swapping”).
Consistency: (e) holds twice in one deck and is the course’s only purpose-built composition picture. (a)–(d) are one or two pages each.
The large worked example
10a p13 — the only whole-system class diagram in the course — is drawn in a completely different style from the rest of 10a:
- Single-compartment boxes, name only, pastel fills with matching darker strokes.
- Sampled fills
#D0E0F0blue /#D0E0D0green /#F0E0C0orange, with strokes#6080B0/#80B060/#D09000. These are the draw.io / diagrams.net default shape colours, matched exactly — this figure was built in draw.io with stock styling, not drawn to match the deck. - Dashed lines with small open arrowheads for association/dependency (
WTController→WTView,WTModel→Tank), solid lines with the usual filled triangle for inheritance. - Tiny
1/Nmultiplicities at the line ends. - Green fill appears on
Tank,TileandEnemy— the three classes that have subclasses. This is my inference from one figure, andBattlefield(blue, no subclasses) is consistent with it whileWTView(orange, alone) is not explained. Do not rely on it.
Reference and memory diagrams
The course does not draw its own reference diagrams. It uses Python Tutor.
pythontutor.com output is embedded as a screenshot in 07b p7, p12 and 07c p13, p14, and named as a live-demo cue five times in 02a (p22, p24, p25, p26, p27, captioned Python Tutor 1. through Python Tutor 5.).
The Python Tutor rendering, as it appears in those screenshots:
- Two columns under bold headers
Frames(left) andObjects(right). - A frame is a pale blue box with a bold title (
Global frame) and one row per name; each row isnameright-aligned against a value cell. - An object is a pale yellow box with a small red-brown type caption floating above it —
Point class,Point instance,function. - An attribute inside an instance is a two-cell row: grey name cell, white value cell.
- A reference is a curved blue-grey arrow from a frame slot to the object.
- Aliasing is shown by two arrows converging on one object (07c p14), versus two arrows to two separate objects for equal-but-distinct values (07c p13).
Consistency: two decks, four screenshots, plus five named references in a third deck spanning week 2 to week 7. Treat Python Tutor as this course’s canonical memory picture.
Bit and memory notation
Established in 02a and legended explicitly on p4.
- A bit is a square cell. Filled black = on/1. White with a black outline = off/0. 02a p4 draws the two side by side and labels them
OnandOff. - Held on 02a p6, p7, p8, p9, p10, p11, p12 — seven further pages.
- A bit string is a horizontal row of contiguous squares, read left to right, with
. . .after the last cell for continuation (02a p10, p11). - Memory is rows of words stacked vertically, each row prefixed in the left margin by its address as a small decimal number (02a p12: 381–388).
- Enumerating all n-bit patterns stacks one row per pattern (02a p7, p8, p9).
Consistency: very strong within 02a. Never used again — no later deck draws a bit.
Data-structure and algorithm-trace diagrams
12b p2: “Note: The diagrams from today’s lecture are taken from runestone.academy.”
This is the closest thing CSSE1001 has to a textbook lineage, and it governs every sorting and merge-tree figure in 12b (p4, p7, p10, p13, p14). Those figures are Runestone Academy’s, not the lecturer’s, which is why their visual language matches nothing else in the course.
List cells. A list is a horizontal row of adjacent square cells with a thin grey border and a soft drop shadow, one integer per cell in small sans-serif, centred. (12b p4, p7, p10, p13, p14)
Shading marks state. White = untouched; grey fills mark the cells the current step is acting on or the region already sorted. The exact meaning of each grey level is never legended — see Not established.
A trace runs top to bottom. Each row is one step; time advances downward. (12b p4, p7, p10)
Step captions sit to the right of each row, small black sans-serif, in the present tense of what just happened: 93 is largest, inserted 26, Exchange / No Exchange, 91 in place after first pass. (12b p4, p7, p10)
Movement arrows are thin black orthogonal arrows drawn above the row, running from source cell to destination cell (12b p4). A whole pass gets a long labelled arrow spanning the figure above everything else — First pass (12b p10).
Recursion trees (merge sort, 12b p13–p14) are drawn as binary trees of list-rows:
Merge Sort – Winding(p13): the full list at the top, splitting downward, arrows pointing down from a list to its two halves.Merge Sort – Unwinding(p14): the singletons at the top, arrows pointing down into each merged result, ending in the sorted list at the bottom.
Both use downward arrows. The recursion direction is carried by the slide title and by which end of the tree holds the whole list — not by arrow direction. This is easy to get wrong.
Mathematical and logical notation
Truth tables (03b p6, p7). A 3×3 grid with visible black rules; the operator name sits in the top-left cell in cyan monospace (and, or); the header row and header column carry the operand values in black monospace; a double rule separates the headers from the body. The one semantically interesting result is coloured magenta — the single True for and (p6), the single False for or (p7).
Function signatures are given above the table, centred, mixing monospace names with maths: and : 𝔹 × 𝔹 → 𝔹. Also > : ℤ × ℤ → 𝔹 (03b p5) and P : ℕ → {True, False} (12a p11).
Blackboard bold for domains — 𝔹 booleans (03b p4, p5, p6, p7), ℤ integers (03b p5), ℕ naturals (12a p11, p13). 𝔹 = {True, False} is defined with the Python literals inside the set, in monospace (03b p4).
Python literals stay in monospace inside maths. True and False are never italicised into maths variables.
Implication and quantifiers use ⟹ and ∀: (P(0) and (P(n) ⟹ P(succ(n)))) ⟹ ∀m ∈ ℕ, P(m) (12a p11). Note and stays as the Python keyword in monospace even inside a mathematical statement.
Contradiction is ⇒⇐ (02a p20).
Displayed maths is centred on its own line, in magenta when it is the point being made (02a p20, 12a p11).
Arrow chains stand in for flow diagrams. Simple pipelines are written inline as text with → rather than drawn: state change → _check_invariants → valid (08b p8), parent → child → grandchild (10b p12), Task + TodoList → Model (domain) (11a p8). Consistency: three decks. This is why the course has so few real flow diagrams.
Geometric and proof figures
The chessboard-tiling figures for the induction proof (12a p12, p14, p15):
- The construction is drawn in cyan solid lines.
- The underlying reference grid is grey dashed.
- The distinguished (uncovered) square is a filled magenta disc.
- Dimensions are annotated with cyan extension lines outside the figure, labelled in black serif maths (
2ⁿ,2ⁿ⁺¹), placed below and to the right.
Consistency: three pages, one deck, entirely self-consistent.
The one flow diagram
07a p17 is the only control-flow diagram in the 726 pages. It shows try/except/else/finally:
- Nodes are rounded rectangles with a hand-drawn, wobbly grey stroke (a sketch/xkcd style).
- The node label is the bare Python keyword in monospace, coloured per keyword:
tryteal,exceptmagenta,elseblue,finallypurple. finallyis drawn with a dashed sketchy border; the other three are solid.- Flow runs top to bottom, with curved grey arrows looping out to the left.
- Edge captions are bold sans-serif, placed below the arrow they describe: Run the code under try, Execute the code under except when there is an exception, No exceptions? run the code under else after try, Always run this code.
- Status glyphs sit outside the flow: a purple circled ✗ beside the try→except path, a green circled ✓ beside the try→else path, a blue circled i beside
finally.
This is a single instance. It does not establish a general flowchart convention for the course — see Not established.
The LEGB diagram
07b p13 draws name resolution as a vertical cascade:
- Four levels listed top to bottom, each with its initial letter bold — Local, Enclosing, Global, Built-in.
- Between consecutive levels, a large red hook arrow with the small red caption
If not foundto its left. - The cascade terminates in bold red
Error!.
Red marks the failure path. Single instance.
Naming and capitalisation
The three rules the course states in words, not just in examples:
| Kind | Rule | Evidence |
|---|---|---|
| Variables, functions | lowercase, words separated by underscores — descriptive_variable_name |
03a p25 |
| Classes | CamelCaps — “That is ClassNamesAreLikeThis” |
07c p7 |
| Constants | SNAKE_CASE_CAPS |
07b p5 |
03a p24 states the course follows Google’s PEP, “a variant of PEP8”, with both linked as lavender rounded chips. 03a p26: lines must be strictly less than 80 characters.
These rules govern labels in diagrams too. UML boxes use CamelCaps class names (DeliveryRobot, WTController, DroneFlight) and snake_case members (_check_invariants(), has_solar_panels, battery_level) throughout 10a, 10b, 07c and 08a.
Do/don’t pairs. Compared alternatives go in a two-column table headed Yes and No in magenta italic, with a single rule under the headers and no other lines — good on the left, bad on the right (03a p25, p28). The variant form labels two separate ruled listings Not helpful / Helpful in magenta italic (03a p27). Inside dark-theme code screenshots the same judgement is made with an all-caps comment — # BAD! / # GOOD! (08b p7).
Figure sourcing and attribution
No textbook is cited as a figure source anywhere. A full-text search of all 25 decks and the course profile for textbook, figure-source and adaptation language returns only the four items below. The course profile prescribes no textbook at all.
| Attribution | Where | Scope |
|---|---|---|
Based on slides from Dr. Azadeh Ghari-Neiat |
Title page of 07a, 07b, 07c, 08a, 08b, 09a, 09b, 10a, 10b, 11a | Slide lineage, not figure lineage |
Based on slides from Dr. Azadeh Ghari-Neiat and Dr. Paul Vrbik |
07b title page | as above |
Note: The diagrams from today's lecture are taken from runestone.academy. |
12b p2 | All sorting figures in 12b |
Image source: www.freepik.com |
09a p9 | That slide’s stock art |
Images are from WIRED |
09b p2, p3 | Those slides’ photos |
Inspired by the example of MIT6.100L slide. |
07c p10 | The blueprint/house analogy — an idea, not a figure family |
Placement. Credits are set in tiny centred or bottom-right roman type beneath the figure (09a p9, 07c p10) or in the bottom-right corner of the slide (09b p2, p3).
10b p9 refers to “the course notes” as the source of a code snippet — the course has its own written notes (delivered via Ed Lessons) which are not among these materials and may carry conventions this note cannot see.
Page furniture
- Slide titles: dark blue
#3030B0, serif, upper-left, sentence case with title-case content words.Optional Content:is used as a prefix for non-examinable material (10b p5). - Footer:
n / Nin tiny grey at the bottom-right. Unreliable — see How to read the citations. - Title slide: course code and title in blue, lecture number and name in magenta italic, lecturer, date, then the attribution line. (10a p1, 09a p1, 09b p1, 10b p1, 11a p1)
- QR-code slides: a large centred QR code with the URL in small serif beneath, flanked by decorative 3D clip art, no title (07a p19, 07b p18, 09b p19).
Inconsistencies
Places where the course does the same thing more than one way. Both readings are recorded; a decision is needed before drawing.
1. Two entirely different UML idioms inside one deck
10a p4–p11 draws three-compartment black-outlined class boxes with magenta relationship lines, orthogonal routing and no fills. 10a p13 draws single-compartment pastel-filled draw.io boxes with dashed dependency arrows. Same deck, same lecture, same subject. 10b p19 adds a third variant: single-compartment boxes with navy #103040 outlines. Decide: compartments or not, fills or not, box outline colour.
2. Class boxes are drawn four incompatible ways before week 10
Three-compartment black box (10a p6); attributes-box-above-methods-box with the name outside and magenta outlines (07c p6); attributes-left/methods-right around a central black name box (08a p2); plain filled rectangle with name only (09b p2, p4). Decide which is canonical for pre-UML material.
3. Inheritance connectors: three styles
Orthogonal bracket with no arrowhead (09b p2, p3); straight blue lines each with its own arrowhead, overlapping at the parent (09b p4, p5, p6); orthogonal bracket with a filled triangular arrowhead (10a p4, p7–p11; 10b p19). Decide.
4. Hierarchy box colour: uniform vs. per-child
09b p2/p3 fill every box the same steel blue. 09b p4/p5/p6 make the root black and give each child its own colour. The two appear two pages apart. And 10a p13 uses a third scheme where colour may track “has subclasses”. Decide whether fill colour means anything at all.
5. Warning heading: red or purple
Red #F00000 in 12a p10 and 04b p14. Purple #7030A0 in 07b p6. Decide.
6. Two greens for the same role
Question / Exercise / Example / Task are #109050 in the LaTeX decks (02a p5, 03b p11) but #00B050 in the PowerPoint ones (10a p12, 11a p8). Same meaning, two hexes. Additionally 01a p25 sets Question in a magenta/crimson rather than either green (observed visually; my colour sample of that page missed the heading). Decide one green.
7. Boxed-token highlight colour is unfixed
Purple (07c p9, p16), magenta (07a p18), blue-and-purple keyed to two referents (09b p9). Decide.
8. Three code presentations
Ruled + line-numbered LaTeX listings (most decks); dark-theme screenshots of an IDE (09b p8–p13, p16; 10b p2, p4, p5; 08b p7); and plain unruled, unnumbered monospace (07a p16, p20). 09b switches between the first two within a single deck. Decide.
9. Summary styling
Purple block heading (02a p28, 07a p21, 07b p19); blue slide title (10a p14, 11a p14); magenta (09b p18). Decide.
10. Image credits are given inconsistently
09a p9 and 09b p2/p3 credit their stock photography. 01a p23–p29 (Ada Lovelace, Grace Hopper, the Jacquard loom, punch cards, the first computer bug), 07c p6/p10, 08a p2/p4 and 12a p4–p9 (the meme sequence) credit nothing. Decide a credit policy.
11. Bit-string reading order
02a p7–p9 enumerate n-bit patterns by toggling the leftmost cell fastest (off-off, on-off, off-on, on-on), which reads the leftmost cell as least significant. 02a p11 then interprets a word as 1·2³² + 1·2³¹ + … + 1·2⁰, reading the leftmost cell as most significant. If you draw a numbered bit string, decide which end is the high bit.
12. Exercise as heading vs. divider
A green block heading in 03b p11, 12b p5, 09b p17, 10a p12, 11a p8 — but a full magenta italic divider slide in 08b p11. Decide.
Not established by the source
Conventions a diagram in this course will plausibly need, that the materials simply do not settle. This is where the risk of invention lies.
No general flowchart convention. The only flow diagram in 726 pages is 07a p17’s sketch-style try/except figure. There is no established shape vocabulary (no decision diamond, no terminator, no process box), no arrow style, and no rule for labelling branches. If you need a flowchart, you are inventing one. Note that the course’s habit is to write flow as an inline → chain (08b p8, 10b p12, 11a p8) rather than draw it — consider doing that instead.
No MVC diagram. The entire MVC deck (11a, 14 pages) contains no architecture diagram. The Model/View/Controller relationship is given as a six-item numbered list (11a p6, p13) and a four-column table (11a p5). The only place the three appear as boxes is 10a p13, where they are three unremarkable draw.io rectangles among thirteen. There is no established shape, layout, arrow direction, or colour for an MVC diagram in this course.
No hand-drawn reference or memory diagram. The course never draws its own variable/object box-and-arrow picture — it screenshots Python Tutor (07b p7/p12, 07c p13/p14). If you need a reference diagram that Python Tutor cannot produce, there is no house style to follow.
No list or aliasing diagram. 04b (non-primitive data, 45 pages) teaches aliasing, copying and pass-by-reference entirely through REPL transcripts — mutating ys and observing xs change (p10, p12, p13). Not one box-and-arrow picture of a list. The idea of “two names, one list” is never drawn outside Python Tutor.
Grey-level semantics in the sorting traces are never legended. 12b p4, p7, p10 use at least three shades — white, light grey, darker grey — and no slide says which is “being compared”, which is “sorted”, and which is “just moved”. Since these figures are Runestone’s, the course has no stated rule to appeal to.
No stated meaning for fill colour in class boxes. 09b p5’s brick red, teal and orange appear decorative; 10a p13’s green may mark classes with subclasses but this is one figure and WTView’s orange contradicts any simple reading. There is no colour key anywhere.
No convention for showing a method body, call stack, or sequence of calls. Despite 12a (recursion, 47 pages) there is no call-tree or stack-frame diagram of the course’s own making — recursion is taught with memes (p4–p9), induction on chessboards (p12–p15) and code. No UML sequence diagram, activity diagram, state diagram or object diagram appears anywhere in the course.
No rule for typing method returns in UML. 10a p6 writes +info(): str; 10a p7–p11 write +info(). Both are the same method on the same class in the same deck.
No hex values are ever published. Every colour in this note was sampled from the rendered PDFs. The course states no palette, so a redrawn figure matching these hexes matches the slides by measurement, not by declaration.
Abstract classes have no notation. 10b p3–p5 teaches abstract base classes in prose and code only. UML’s italic-name convention for abstract classes is never used; Shape is never drawn.
Line weights, font sizes and box dimensions are never specified, and vary between the two slide families.
The eight unread decks. 00-welcome, 01b, 02b, 04a, 05a, 05b, 06a, 06b were not read as images. They contain no embedded raster images (except 00-welcome’s six photo pages) and are in the LaTeX family, so they are unlikely to hide a new idiom — but this note cannot rule it out.
The written course notes. 10b p9 cites “the course notes” as a source. Those notes are delivered through Ed Lessons and are not part of these materials. If they contain diagrams, they may establish conventions that contradict this note.
See also
- 2025-10-07-uml — Lecture 10A’s content
- uml — the UML reference note
- python-pep8-style-guide — the naming rules cited above
- csse1001 — course index
Python Comprehensions
A comprehension is a concise way to build a list or dictionary directly from an iterable, without writing an explicit accumulator for-loop.
List comprehension
>>> [k**2 for k in range(4)]
[0, 1, 4, 9]
Equivalent to:
>>> acc = []
>>> for k in range(4):
... acc.append(k**2)
sum(... for ...), without the surrounding [], computes a running total directly. The bracket-less form is a generator expression, and so totals without building the intermediate list.
>>> sum(k**2 for k in range(4))
14
Dictionary comprehension
Same shape, but the output expression is a key: value pair and the braces are {}:
>>> {x: f"value is {x}" for x in range(3)}
{0: 'value is 0', 1: 'value is 1', 2: 'value is 2'}
Useful for assigning default values across a set of keys:
>>> {x: 0 for x in "ABC"}
{'A': 0, 'B': 0, 'C': 0}
Duplicate keys collapse — iterating a string with repeated characters still yields one entry per distinct character:
>>> cs = "hello world"
>>> {x: cs.count(x) for x in cs}
{'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
Nested comprehensions
Multiple for clauses can appear in one comprehension. The order of the for clauses matters — it matches the order they’d be nested as for-loops:
>>> [(a, x) for a in "AB" for x in range(2)]
[('A', 0), ('A', 1), ('B', 0), ('B', 1)]
>>> [(a, x) for x in range(2) for a in "AB"]
[('A', 0), ('B', 0), ('A', 1), ('B', 1)]
Filtering
A trailing if filters which elements are included:
>>> [x for x in range(101) if not (x % 3) and not (x % 7)]
[0, 21, 42, 63, 84]
The general pattern
[x for x in xs if P(x)]
[x for x in xs for y in ys if P(x, y)]
[x for x in xs for y in ys for z in zs if P(x, y, z)]
...
where P is some predicate.
Figure 8: The three parts of a comprehension, named on the first two forms of the general pattern: output expression, generator clause and filter. Magenta is the output expression, blue the first generator clause, purple the second. That key covers the boxed code only: the purple arrow labelled outer loop, then inner and the purple line beneath the second form are annotations, not a fourth part.
The same three parts appear in a dictionary comprehension, except the output expression is a key: value pair.
True/False as 1/0
True/False behave as 1/0 in arithmetic — a common idiom for counting how many elements of an iterable satisfy some condition. It works because Python’s bool is a subtype of int.
>>> True + True + False
2
>>> sum(x > 0 for x in [-1, 2, 3, -4])
2
all and any
Python’s built-in all(xs)/any(xs) check whether every/some element of xs is truthy:
>>> all(['A' <= x <= 'Z' for x in "HELLO WORLD"])
False
>>> any(['A' <= x <= 'Z' for x in "HELLO WORLD"])
True
Careful: redefining a function named
alloranyin your own code shadows these built-ins for the rest of that scope. 2025-08-25-comprehensions’s exercises do exactly that, deliberately, to reimplement them.
See python-for-loops for the equivalent for-loop/accumulator forms these shortcut.
Python Dictionaries
Definition (Dictionary). A dictionary in Python is a data-structure that stores
tuple(key, value)pairings. Python has a “magic” hash function to find a key among the tuples fast. Dictionaries are not ordered and are mutable.
Hash tables are a candidate for the most important/useful data-structure in computer science.
The dictionary is not a new idea so much as a generalised index: see Lecture 4B’s hash-function section for two hand-rolled encodings, and the figure there showing a key being turned into a list position by two different hash functions. dict is what you get when Python supplies that hash function for you, for keys of any (immutable) type. The reason a dictionary has no ordering is precisely that the keys can be of mixed type.
Creating and indexing
>>> h = {
... "red": ["apple", "firetrucks", "cars"],
... "yellow": ["banana", "cars"],
... "blue": ["sky", "cars"]
... }
>>> h["blue"]
['sky', 'cars']
>>> h["green"]
KeyError: 'green'
>>> h["green"] = ["leaves"] # fine, because we're assigning not retrieving
An empty dictionary is dict() (or {}).
keys, values, items
>>> h.keys()
dict_keys(['red', 'yellow', 'blue'])
>>> h.values()
dict_values([['apple', 'firetrucks', 'cars'], ['banana', 'cars'], ['sky', 'cars']])
>>> h.items()
dict_items([('red', ['apple', 'firetrucks', 'cars']), ('yellow', ['banana', 'cars']), ('blue', ['sky', 'cars'])])
items() is the one that shows the definition literally: each pairing comes back as a (key, value) tuple.
clear and copy
>>> f = h.copy()
>>> h.clear()
>>> h["blue"]
KeyError: 'blue'
>>> f["blue"]
['sky', 'cars']
Like list’s .copy() (see python-lists), dict’s .copy() is only a shallow copy — mutable values are still shared:
>>> f = h.copy()
>>> h["blue"].append("windex")
>>> h["blue"]
['sky', 'cars', 'windex']
>>> f["blue"]
['sky', 'cars', 'windex'] # shallow copy -- same underlying list
Read the two transcripts together: clear() empties the dictionary h without touching f, because f is a different dictionary object — but h["blue"].append(...) reaches through both dictionaries to the one list they share. Same shallow/deep split as the shallow-copy figure in python-lists.
get
.get(key) is a safer alternative to h[key] — it returns None instead of raising KeyError if the key is missing:
>>> h.get("red")
['apple', 'firetrucks', 'cars']
>>> h["green"]
KeyError: 'green'
>>> h.get("green")
None # safer, because no error is thrown here
Without a method, the same “avoid a KeyError” pattern is written explicitly:
>>> if key in table: # avoiding KeyError
... table[key] += 1
... else:
... table[key] = 0
This is a sketch of the membership-test idiom, not a working counter. As a frequency counter the else branch would have to be table[key] = 1 — a key seen for the first time has been seen once, not zero times.
Warning: keys must be immutable
The keys of a dictionary must be an immutable type (see python-primitive-data-types and python-lists):
>>> d = dict()
>>> d[ [1,2,3] ] = 1
TypeError: unhashable type: 'list'
>>> d[ (1,2,3) ] = 1 # tuples are immutable
>>> h = dict()
>>> d[ h ] = 1
TypeError: unhashable type: 'dict'
“Unhashable” is the error message’s way of saying the same thing the definition does: a key has to be something the hash function can turn into a fixed location, and a value that can change underneath you cannot be.
Python For-Loops
A for-loop is a loop that repeats code for every member of a group (an iterator), in order:
for <name> in <iterator>:
<code>
Iterating over strings, lists, and dictionaries
A for-loop iterates a string’s characters, a list’s elements, or a dictionary’s keys (in each case, in order):
>>> for x in "abcd":
... print(x)
a
b
c
d
>>> for x in ['a', 2, 'c']:
... print(x)
a
2
c
>>> for key in {"red": 1, "blue": 2}:
... print(key)
red
blue
The looping name retains its final value after the loop exits.
Nested for-loops
Python disallows empty loop bodies — use pass (the empty instruction, which has no effect) as a placeholder when a loop body needs no code yet:
>>> for d in "01":
... for a in "xy":
... pass
... print(d + a)
0y
1y
Accumulator pattern
An accumulator is a variable a loop uses to build up an aggregate value across iterations:
>>> acc = ""
>>> for x in "abcd":
... acc = acc + x
>>> acc
'abcd'
range
range([start], stop[, step]) builds an iterator of numbers (square brackets denote optional arguments), similar to list slicing:
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(2, 7))
[2, 3, 4, 5, 6]
>>> list(range(2, 7, 3))
[2, 5]
>>> list(range(2, 7, -1))
[]
>>> list(range(7, 2, -1))
[7, 6, 5, 4, 3]
One rule accounts for all of these: the walk starts at start, hops by step, and yields every value it lands on that is still short of stop in the direction it is travelling. So stop is never produced, and start is produced only when the walk produces anything at all — range(2, 7, -1) is empty because a negative step walks down from 2, away from 7, and 2 is already past 7 going that way, so not even start comes out.
Figure 9: Four of the range calls above on one number line, ordered so the negative step that works is read before the one that does not. Filled dots are values the range produces; a grey hollow dot is stop, which it never produces; the red hollow dot on the bottom row is start, which that call never produces either. Magenta marks the answer and red the failure path. This is the half-open reading that range shares with list slicing.
range returns a range object, not a list — range(10) echoes as range(0, 10) and type(range(10)) is <class 'range'>. Wrap it in list(...) to see its contents.
Commonly used to walk through a list by index: for k in range(len(xs)):.
enumerate
enumerate(xs) pairs each element of xs with its index, roughly enumerate([x0, ..., xn]) == [(0, x0), ..., (n, xn)] (it actually returns an iterable of tuples, not a list):
>>> for k, x in enumerate(["a", "b", "c"]):
... print(k, x)
0 a
1 b
2 c
For-loops vs. while-loops
Every for-loop can be rewritten with only a while-loop:
>>> for x in xs:
... ...
>>> k = 0
>>> while k < len(xs):
... x = xs[k]
... ...
... k += 1
The reverse isn’t always true — a while-loop whose number of repetitions isn’t known in advance (e.g. repeatedly prompting a user until they enter valid input) can’t be rewritten as a for-loop.
Out-of-place vs. in-place
Building a new accumulator (e.g. a fresh list) without touching the original input is an out-of-place computation. An in-place change instead mutates the input directly — covered with lists and the object-oriented part of the course.
See python-comprehensions for a more concise way to write many accumulator-style for-loops.
Python Lists
A list is a mutable ordered collection of elements. These elements are not necessarily of the same type. Square brackets [] are used to create lists in Python.
>>> xs = [1, "apple"]
>>> type(xs)
<class 'list'>
>>> xs[0]
1
>>> xs[0] = 2*xs[1]
>>> xs[0] # note: lists are mutable
'appleapple'
Comparison
Lists compare point-wise from position zero:
>>> [1, 2, 3] < [4, 5, 6]
True
>>> [7, 2, 3] < [4, 5, 6]
False
>>> [] < [1]
True
The second line is the one to read carefully: the comparison stops at position zero, where 7 < 4 is False, and never looks at positions one and two.
Membership
>>> 1 in [1, 2, 3]
True
>>> 0 in [1, 2, 3]
False
>>> 123 in [1, 2, 3]
False
>>> [1] in [1, 2, 3]
False
in tests for an element, not a sub-list — the last line is False because [1, 2, 3] contains the integer 1, not the list [1].
Adding elements: append, extend, concatenation
xs + [y] creates a new list, which must be reassigned back to xs to have an effect:
>>> xs = [0, 1, 2]
>>> xs = xs + [3]
>>> xs
[0, 1, 2, 3] # "this is the original list updated"
Read the comment as a statement about the value of xs, not about the object: xs = xs + [...] builds a new list and rebinds xs to it (see the aliasing transcript below), which is exactly why it breaks an alias where append does not.
Alternatively, using a method that list provides — xs.append(y) mutates xs in place:
>>> xs = [0, 1, 2]
>>> xs.append(3)
>>> xs
[0, 1, 2, 3]
append adds its argument as a single new element, even when that argument is itself a list:
>>> xs = [1, 2, 3]
>>> xs.append([4,5])
>>> xs
[1, 2, 3, [4, 5]]
xs.extend(ys) instead appends every element of ys individually — code similar to xs = xs + ys:
>>> xs = [1, 2, 3]
>>> xs.extend([4,5])
>>> xs
[1, 2, 3, 4, 5]
Aliasing
Take care when (trying to) copy lists. Assigning one list variable to another does not copy it — both names refer to the same list object:
>>> xs = [1, 2, 3]
>>> ys = xs
>>> ys[-1] = 9
>>> ys
[1, 2, 9]
>>> xs
[1, 2, 9]
Whether an operation preserves this aliasing relationship depends on whether it mutates the list in place or creates a new one:
>>> xs = [1, 2, 3]
>>> ys = xs # ys is an alias of xs
>>> xs.append(4) # appending to a list
>>> ys
[1, 2, 3, 4]
>>> xs += [5] # appending to a list
>>> ys
[1, 2, 3, 4, 5]
>>> xs = xs + [6] # concatenating two lists
>>> ys
[1, 2, 3, 4, 5] # aliasing relationship broken!
The trap is that xs += [5] and xs = xs + [6] look like the same operation and are not: the first mutates the object both names share, the second builds a new object and rebinds only xs.
Figure 10: What the transcript above is doing to memory. In (a) xs and ys are two names for one list object, so the in-place operations append and += are visible through both. In (b) xs = xs + [6] builds a second list object and rebinds xs to it; ys still refers to the original, which is what aliasing relationship broken means. The layout is Python Tutor’s: frames on the left in pale blue, objects on the right in pale yellow, a reference as an arrow, and aliasing as two arrows converging on one object.
.copy() breaks the alias for a flat list:
>>> xs = [1, 2, 3]
>>> ys = xs.copy()
>>> ys[-1] = 9
>>> xs
[1, 2, 3]
>>> ys
[1, 2, 9]
Passing lists to functions
A more nuanced case is when passing lists (but really list references) to functions — mutating a parameter inside a function mutates the caller’s list too:
>>> def foo(ys):
... ys[0] = -100
>>> xs = [1, 2, 3]
>>> foo(xs)
>>> xs
[-100, 2, 3]
This is the same picture as (a) in Figure 10, with ys being a name in foo’s frame rather than the global one.
Nested lists and matrices
A list can have another list as an element:
>>> xs = [ [1,2], [5,6,7] ]
>>> len(xs)
2
>>> len(xs[-1])
3
len counts the outer elements — two, not five.
A matrix can therefore be represented by a list-of-lists in Python:
\[\mathbb{A} = \begin{bmatrix} 1 & 2 & 3 \\ 4 & 5 & 6 \\ 7 & 8 & 9 \end{bmatrix} \equiv \texttt{[[1, 2, 3], [4, 5, 6], [7, 8, 9]]}\]
>>> ass = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> ass[-1]
[7, 8, 9]
>>> ass[1:3]
[[4, 5, 6], [7, 8, 9]]
>>> ass[1]
[4, 5, 6]
>>> ass[1][-1]
6
>>> ass[1,-1]
TypeError: list indices must be integers or slices, not tuple
The last line is the one worth remembering: a nested list is indexed with repeated brackets, ass[1][-1]. The comma form ass[1,-1] is a tuple and is a TypeError for a list.
Deep copying
.copy() only performs a shallow copy — nested mutable elements (like inner lists) are still shared between the original and the copy:
>>> ass = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> bss = ass.copy()
>>> bss[0][0] = 0
>>> bss
[[0, 2, 3], [4, 5, 6], [7, 8, 9]]
>>> ass
[[0, 2, 3], [4, 5, 6], [7, 8, 9]] # A was changed!
Figure 11: Why ass changed. bss = ass.copy() made a genuinely new outer list — that is why bss and ass are two distinct objects — but it copied the outer list’s three references, not the objects they point at, so both outer lists share the same three inner lists. Writing bss[0][0] = 0 reaches through a shared reference and the change shows up through ass as well. For this to work as expected we need a deep-copy, which is not built-in — see copy.deepcopy. Magenta marks the mutated cell.
A true independent copy of nested structures needs a deep copy, which is not built into list — see copy.deepcopy.
Slicing
>>> xs = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> xs[3:6]
[3, 4, 5]
>>> xs[::2]
[0, 2, 4, 6, 8]
>>> xs[7:2:-2]
[7, 5, 3]
The three fields are start:stop:step with stop exclusive: xs[3:6] takes positions 3, 4 and 5; xs[::2] takes every second element of the whole list; and a negative step makes xs[7:2:-2] walk backwards from position 7, stopping before position 2.
Type hints
Warning. Type-hinting lists (e.g.
list[int]) is a new feature in Python 3.9 and greater.
Unpacking into function arguments
It is possible to “unbracket” a list when passing it to functions, with *:
>>> def f(x, y, z):
... return x + y + z
>>> x = [1, 2, 3]
>>> f(x)
TypeError: f() missing 2 required positional arguments: 'y' and 'z'
>>> f(*x)
6
Tuples
Tuples are immutable ordered collections whereas lists are mutable ordered collections. Both can be sliced and indexed. See python-primitive-data-types; a tuple’s immutability is what makes it usable as a dictionary key, where a list is not — see python-dictionaries.
Python While Loops
A loop is a control structure that repeats code that belongs to it. A while-loop is a loop that repeats code while some condition is satisfied:
while <condition>:
<code>
The condition is checked before every repetition (including the first) — if it’s false to begin with, the loop body never runs at all:
>>> x = 0
>>> while False:
... print(x)
... x += 1
>>> # nothing prints
See the while-loop control-flow figure in 2025-08-18-while-loops for a picture of this.
Augmented assignment operators
| Operator | Equivalent to |
|---|---|
x += y |
x = x + y |
x *= y |
x = x * y |
x /= y |
x = x / y |
x %= y |
x = x % y |
These are the four used in the course. They are what makes an accumulator loop readable:
>>> x = 0
>>> while x < 10:
... x += 1
>>> x
10
break
The break keyword terminates the (innermost) loop immediately and continues with the rest of the program — so code after it inside the loop body is unreachable:
>>> while True:
... print("hello")
... break
... print("world")
hello
Simulating a do-while
A do-while (or repeat-until) is a while-loop variant available in other languages but not natively supported in Python. It runs its code at least once, because the condition is only tested after the body:
do:
<code>
while <condition> # not valid Python syntax
Figure 12: The do-while as a flowchart. Compare the while-loop figure in 2025-08-18-while-loops: the body is above the test rather than below it, so the body always runs once before C is ever evaluated, and the True edge is the one that loops back.
Although not natively supported in Python, we can simulate one with while True and a break (some programmers prefer 1 to True):
>>> x = 0
>>> while 1:
... x += 1
... if x > 0:
... break
>>> x # x retains its value outside the while
1
x ends at 1, not 0: the body ran once before the exit test was reached, which is the whole point of the shape.
User input
x = input() waits for input from the keyboard and assigns it to x, always with type(x) is str. Numeric input therefore has to be converted — int(input("Guess: ")).
Random number generation
Random number generation is handled by an external library. It is not built-in and therefore must be imported. Importing the single command:
>>> from random import randint
>>> randint(1, 6) # chosen uniformly over the interval
2
or the entire library:
>>> import random
>>> random.randint(1, 6)
2
Both endpoints are included: randint(1, 6) is the course’s six-sided die, and its prompt reads Guess in [1..6].