01A.4 Core Data Structures: Lists, Tuples, Dictionaries and Sets
Almost everything an AI application touches is one of four built-in containers: a list of messages, a dict (Python's word for what JSON calls an object), a set of ids to deduplicate, or a tuple of values that belong together. This lesson builds the complete mental model those containers rest on — names pointing at objects, mutability, aliasing and copying — and then takes each structure in turn: every method that matters, the traps that produce silent bugs, and the collections helpers engineers reach for daily. It ends by assembling the support-ticket toolkit that the rest of Module 01A keeps extending: a list of ticket dicts you can filter, group, count, sort, deduplicate and index.
What you'll learn
- The object model underneath everything: names are labels, objects are the data, assignment binds rather than copies, and mutability decides what is safe to share
- Lists completely: indexing and slicing, every mutation method including slice assignment,
sortvssortedwithkeyand stability, searching, copying correctly, nested lists, the[[0] * n] * mtrap, lists as stacks and queues,collections.deque, and unpacking with* - Tuples: packing and unpacking, the
(x,)trap, shallow immutability, tuples as dictionary keys and return values,namedtuple, and whydataclassusually wins (preview of 01A.6) - Dictionaries — the most important structure in AI code, because JSON objects are dicts: access with
[]/get/setdefault, the insertion-order guarantee,update, the|/|=and{**a, **b}merge forms, views, hashability and what can be a key, safe traversal of nested dicts with aget_pathhelper, lists of dicts as records, anddefaultdict,Counter,OrderedDictandChainMap - Sets and
frozenset: membership speed, set algebra, subset tests, the mutation API (add/removevsdiscard/update/in-place operators), deduplication and order-preserving dedupe withdict.fromkeys - How to choose a structure: Big-O costs explained for freshers, a real (machine-dependent) timing demonstration, a decision table, and the
collections,heapq,bisectandarraymodules - The ticket-triage data toolkit: group by status, count by category, top-N by priority, find duplicate ids, and build an index by id
What you don't need
- Any Python beyond 01A.1–01A.3. If those are new to you, do them first — this lesson assumes you can write a
forloop, anif, and a function. - API keys or network access. Everything here is pure standard library, offline and deterministic. No API key needed.
- NumPy or pandas. Those are Module 01B, lesson 11; this lesson only points at them where they take over.
Setup
You need Python 3.11 or newer and a terminal with a text editor. As of November 2026 the current stable release is Python 3.15.x, and the supported range is 3.11–3.15 (3.10 reached end-of-life in October 2026 — check python.org/downloads for the live table). The quickest way to get a modern Python is uv:
uv python install 3.13
uv run python --versionor install from python.org / your OS package manager and run scripts with python3 script.py. If your terminal or editor setup is new, Module 00, lesson 00.1 walks through it. Every snippet in this lesson is standard-library only: save it as a .py file and run it.
What you must be able to do after this lesson#
- Explain names, objects and mutability
- Use lists with slicing, mutation methods and correct copying
- Use tuples and unpack them
- Use dicts with get, setdefault and merge forms
- Use sets for membership tests and deduplication
- Choose the right data structure for a task
- Group and count records with dicts and sets
Why this matters for an AI engineer#
You will spend more time shaping data than calling models. Provider APIs speak JSON; JSON decodes into dicts and lists; your code then filters, groups, sorts, deduplicates and re-serializes those structures thousands of times per request pipeline. Choosing the wrong container — a list where a set belongs, a dict you mutate by accident, a tuple you try to update — is the source of most "the data was fine yesterday" bugs.
| You'll hear... | You'll understand it after... |
|---|---|
"The API returned a JSON object — in Python that's just a dict." |
4.1 Creating and reading and 4.9 JSON-compatible shapes |
"The conversation is a list of message dicts." |
4.6 Lists of dicts and 03.2 |
"tool_calls[0].function.arguments is a JSON string — parse it first." |
4.5 Nested dicts and 03.5 |
"Every chunk carries a metadata dict for filtering." |
4.8 The collections helpers and 05.8 |
| "Dedupe these 50,000 ids before embedding." | Part 5: Sets |
"Group the tickets by status for the dashboard." |
4.6 Lists of dicts and Part 7 |
"Why is popleft() on a list so slow?" |
2.7 Lists as stacks and queues |
| "Which structure for this lookup table?" | Part 6: Choosing |
| "Stream events arrive one dict at a time." | 4.5 Nested dicts and 03.3 |
Part 1: Names, objects and mutability#
Everything in this lesson rests on one idea that 01A.1 introduced and 01A.11 revisits: Python names are labels stuck on objects, not boxes that contain values. Understanding this once saves you from an entire family of bugs.
1.1 Assignment binds a name, it does not copy#
When you write b = a, Python does not duplicate a's value. It evaluates a — which names some object — and sticks the label b on that same object:
# names.py
a = [1, 2, 3]
b = a # b is a second name for the SAME list
print("a is b:", a is b) # True: one object, two names
b.append(4) # mutate through either name...
print("a:", a) # ...and both names see it
print("b:", b)a is b: True
a: [1, 2, 3, 4]
b: [1, 2, 3, 4]The is operator asks "do these two names point at the same object?" — different from ==, which asks "do these two objects have equal values?". [1, 2] == [1, 2] is True even for two separate lists; [1, 2] is [1, 2] is False. Lesson 01A.1 covers is vs == in depth; here the takeaway is: is is how you detect sharing.
flowchart LR
subgraph before ["After b = a"]
A1["name: a"] --> O1(("list object<br/>[1, 2, 3]"))
B1["name: b"] --> O1
end
subgraph after ["After m = m + 1 (ints)"]
N2["name: n"] --> O2(("int 10"))
M2["name: m"] --> O3(("new int 11"))
endNumbers work the same way — m = n shares the int, but m = m + 1 doesn't mutate it. Since ints are immutable, Python must create a new object for the sum and rebind m:
n = 10
m = n
print("n is m:", n is m) # True — same object
m = m + 1 # rebinds m to a NEW int; n still names 10
print("n:", n, "m:", m)
print("n is m now:", n is m)n is m: True
n: 10 m: 11
n is m now: False1.2 Mutable vs immutable: the divide that matters#
Every built-in type is either mutable (you can change the object in place) or immutable (any "change" produces a new object):
| Mutable (change in place) | Immutable (operations return new objects) |
|---|---|
list |
int, float, bool, str, bytes |
dict |
tuple |
set |
frozenset |
bytearray |
NoneType (only None) |
Why does this matter so much? Three consequences you'll meet constantly:
- Aliasing is dangerous for mutables. Two names sharing one list see each other's edits. For immutables, "sharing" is harmless — you can never observe it, because there is no way to edit the object.
- Only immutables can be dict keys and set members. A key must be hashable: the object must have a fixed hash value for its whole life, which requires it to be immutable. A list's contents can change, so it can't promise a stable hash — hence
d[[1, 2]] = "x"raises aTypeError("cannot use 'list' as a dict key (unhashable type: 'list')" on Python 3.14; earlier versions print justunhashable type: 'list'). Tuples are the classic key because they're immutable — provided everything inside them is immutable too. - Immutables are safe to share across threads and caches. Passing an immutable to a function can't surprise the caller, because the function cannot change it.
>>> d = {}
>>> d[[1, 2]] = "nope"
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')The full hashability rules get their own section in 4.4.
1.3 Aliasing, shallow copies and deep copies#
When you do want an independent copy of a mutable object, Python offers three levels of "sameness":
| Expression | Result |
|---|---|
b = a |
Alias — same object, two names |
a.copy(), a[:], list(a), copy.copy(a) |
Shallow copy — new outer container, but nested objects are still shared |
copy.deepcopy(a) |
Deep copy — recursively copies everything inside |
# alias_copy.py
import copy
original = {"id": "T-1", "tags": ["urgent", "billing"]}
alias = original # same object
alias["tags"].append("vip")
print("after alias append, original:", original["tags"])
shallow = original.copy() # new dict, SAME inner list
shallow["tags"].append("shallow-only")
print("original:", original["tags"])
print("shallow :", shallow["tags"])
deep = copy.deepcopy(original) # new dict AND new inner list
deep["tags"].append("deep-only")
print("original:", original["tags"])
print("deep :", deep["tags"])after alias append, original: ['urgent', 'billing', 'vip']
original: ['urgent', 'billing', 'vip', 'shallow-only']
shallow : ['urgent', 'billing', 'vip', 'shallow-only']
original: ['urgent', 'billing', 'vip', 'shallow-only']
deep : ['urgent', 'billing', 'vip', 'shallow-only', 'deep-only']Read that carefully: the "shallow" copy still leaked the edit into original, because both dicts point at the same inner list. Only deepcopy gave full independence.
Part 2: Lists#
A list is an ordered, mutable sequence. "Ordered" means items have positions (index 0, 1, 2, ...); "mutable" means you can change the list in place without creating a new one. Lists are the workhorse container: message histories, rows of records, queues of jobs, collections of embeddings you built yourself.
2.1 Creating, indexing and slicing#
# lists_basics.py
scores = [82, 91, 67, 74, 88]
empty = []
also_empty = list()
from_range = list(range(5)) # [0, 1, 2, 3, 4]
print("scores :", scores)
print("scores[0] :", scores[0]) # first element
print("scores[-1] :", scores[-1]) # last element
print("scores[1:4] :", scores[1:4]) # slice: start included, end EXCLUDED
print("scores[::2] :", scores[::2]) # every second element
print("empty :", empty, also_empty, from_range)scores : [82, 91, 67, 74, 88]
scores[0] : 82
scores[-1] : 88
scores[1:4] : [91, 67, 74]
scores[::2] : [82, 67, 88]
empty : [] [] [0, 1, 2, 3, 4]Slicing follows start:stop:step, and the rules are worth memorizing because every data task uses them:
stopis exclusive:scores[1:4]gives indices 1, 2, 3 — three items, not four.- Negative indices count from the end:
scores[-1]is the last item,scores[-2:]the last two. stepskips:scores[::2]takes every second item;scores[::-1]reverses.- Slicing never fails on out-of-range values — it clamps.
scores[0:999]returns the whole list. But indexing does fail:scores[10]raisesIndexError. This asymmetry surprises everyone once.
>>> scores = [82, 91, 67]
>>> scores[10]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
IndexError: list index out of range
>>> scores[1:99]
[91, 67]2.2 The mutation toolkit#
Lists change through methods (and del). Learn which ones modify in place versus return something — mixing them up is a classic bug:
| Operation | What it does | Returns |
|---|---|---|
lst.append(x) |
add x at the end |
None (in place) |
lst.extend(iterable) |
add each item of the iterable at the end | None (in place) |
lst.insert(i, x) |
insert x before index i |
None (in place) |
lst.pop(i) |
remove and return item at i (default: last) |
the item |
lst.remove(x) |
remove first item equal to x |
None (in place) |
del lst[i] / del lst[a:b] |
delete by index or slice | — |
lst.clear() |
remove all items, keep the (empty) list object | None |
lst.reverse() |
reverse in place | None (in place) |
lst.copy() |
shallow copy — new list, nested objects still shared (3.3+) | new list |
lst[a:b] = xs |
replace a range — also inserts and deletes (see below) | — (in place) |
lst += iterable |
extend in place | None |
lst + iterable |
new list with items concatenated | new list |
# lists_mutate.py
scores = [82, 91, 67, 74, 88]
scores.append(95) # one item at the end
scores.extend([60, 77]) # several items at the end
scores.insert(0, 50) # before index 0
print("after appends:", scores)
print("pop() ->", scores.pop()) # removes and returns the LAST item
print("pop(0) ->", scores.pop(0)) # removes and returns index 0
print("scores :", scores)
scores.remove(67) # first item EQUAL to 67 (not index 67!)
print("after remove(67):", scores)
del scores[1:3] # delete a slice in place
print("after del [1:3] :", scores)
scores.clear()
print("after clear() :", scores)after appends: [50, 82, 91, 67, 74, 88, 95, 60, 77]
pop() -> 77
pop(0) -> 50
scores : [82, 91, 67, 74, 88, 95, 60]
after remove(67): [82, 91, 74, 88, 95, 60]
after del [1:3] : [82, 88, 95, 60]
after clear() : []Three traps hiding in that table:
append(x)vsextend(xs):append([1, 2])adds the list as one item;extend([1, 2])adds its items.lst += xsisextend, notappend— a frequent "why is my list nested?" bug.remove(x)matches by value, scanning from the front.remove(67)deletes the first67; if there's no67it raisesValueError. To delete by position usepop(i)ordel.lst + xscreates a new list;lst += xsmutateslst. For immutable elements the difference is invisible; for shared references it matters (see 1.3).
One more mutation form deserves its own paragraph because it's the most powerful: slice assignment. lst[start:stop] = iterable replaces the slice with the iterable's items — and since the lengths may differ, the same statement inserts (lst[i:i] = [x]), deletes (lst[i:j] = []) or replaces (lst[i:j] = xs):
# slice_assign.py
nums = [10, 20, 30, 40, 50]
nums[1:3] = [99] # replace a range — replacement may differ in length
print("replace range :", nums)
nums[2:2] = [25, 35] # an EMPTY slice means pure insertion
print("insert :", nums)
nums[1:4] = [] # an EMPTY replacement means pure deletion
print("delete range :", nums)
# Extended slices ([::k]) must be replaced by the SAME number of items
nums = [1, 2, 3, 4]
nums[::2] = [10, 30] # indices 0 and 2 — two slots, two values
print("step slice :", nums)
try:
nums[::2] = [7] # one value for two slots -> error
except ValueError as e:
print("mismatch ->", e)replace range : [10, 99, 40, 50]
insert : [10, 99, 25, 35, 40, 50]
delete range : [10, 40, 50]
step slice : [10, 2, 30, 4]
mismatch -> attempt to assign sequence of size 1 to extended slice of size 2Unlike del/insert/pop, slice assignment changes the list's length freely on contiguous slices — reach for it whenever you're rewriting a span. Extended slices (lst[::2], lst[::-1]) are positional replacements instead: the right side must supply exactly as many items as the slice selects, or you get a ValueError.
2.3 Sorting: sort vs sorted, key, reverse, stability#
There are two sort functions and the difference matters:
sorted(iterable, ...)returns a new sorted list; the original is untouched. Works on any iterable (tuples, dict keys, sets...).lst.sort(...)sorts in place and returnsNone. Only for lists.
Both take key= (a function producing the sort criterion) and reverse=True.
# lists_sort.py
words = ["fig", "date", "banana"]
print("sorted(words) :", sorted(words))
print("sorted(words, key=len) :", sorted(words, key=len))
print("reverse=True :", sorted(words, key=len, reverse=True))
# Stability: rows with equal keys keep their original relative order.
rows = [("ana", 3), ("bo", 1), ("cy", 3), ("di", 2)]
print("sorted by second item :", sorted(rows, key=lambda r: r[1]))
rank = {"low": 0, "medium": 1, "high": 2, "urgent": 3}
tickets = [
{"id": "T-1", "priority": "high", "created": "2026-10-01"},
{"id": "T-2", "priority": "low", "created": "2026-10-02"},
{"id": "T-3", "priority": "urgent", "created": "2026-10-03"},
{"id": "T-4", "priority": "high", "created": "2026-10-01"},
]
by_pri_then_date = sorted(
tickets,
key=lambda t: (-rank[t["priority"]], t["created"]),
)
print("priority desc, date asc:")
for t in by_pri_then_date:
print(" ", t["id"], t["priority"], t["created"])
nums = [3, 1, 2]
result = nums.sort()
print("nums.sort() returned :", result)
print("nums after sort() :", nums)
# reverse=True reverses the COMPARISON, not the final list — stability
# still applies, so equal keys keep input order (unlike reversed(sorted(...))).
print("reverse=True, stable :", sorted(rows, key=lambda r: r[1], reverse=True))
print("reversed(sorted(...)) :", list(reversed(sorted(rows, key=lambda r: r[1]))))sorted(words) : ['banana', 'date', 'fig']
sorted(words, key=len) : ['fig', 'date', 'banana']
reverse=True : ['banana', 'date', 'fig']
sorted by second item : [('bo', 1), ('di', 2), ('ana', 3), ('cy', 3)]
priority desc, date asc:
T-3 urgent 2026-10-03
T-1 high 2026-10-01
T-4 high 2026-10-01
T-2 low 2026-10-02
nums.sort() returned : None
nums after sort() : [1, 2, 3]
reverse=True, stable : [('ana', 3), ('cy', 3), ('di', 2), ('bo', 1)]
reversed(sorted(...)) : [('cy', 3), ('ana', 3), ('di', 2), ('bo', 1)]What to notice:
- Stability: in
sorted by second item,anaandcyboth have key3and keep their input order. Python's sort is guaranteed stable — equal keys never reorder. That's why the multi-key trick works: sort by the least important key first and let stability preserve it, or (as above) return a tuple key(priority_rank_negated, created)so one comparison decides everything. key=len,key=str.lower,key=lambda t: t["created"]— the key function is applied once per item and its result is what's compared.reverse=Truereverses the comparison, not the final list — the sort stays stable, so equal-keyed items keep their input order even when reversed. The last two lines above prove it:anastill precedescyunderreverse=True, whilereversed(sorted(...))flips them. Andreverse=Truereverses every key in a tuple key at once, so "priority descending, date ascending" can't be expressed with it — that's why the example negates the rank instead.sort()returnsNone.nums = nums.sort()is the classic mistake — it setsnumstoNone. The correct forms arenums.sort()(in place) ornums = sorted(nums)(new list).- For sorting dicts or objects by a field,
key=lambdais fine; for speed on huge lists,operator.itemgetter/attrgetter(covered in 01A.5) avoid Python-level lambda calls.
2.4 Searching: index, count, in#
# lists_search.py
items = ["pen", "pencil", "eraser", "pen", "ruler"]
print("items.index('pen') :", items.index("pen"))
print("items.index('pen', 2) :", items.index("pen", 2))
print("items.count('pen') :", items.count("pen"))
print("'eraser' in items :", "eraser" in items)
print("'marker' in items :", "marker" in items)
try:
items.index("marker")
except ValueError as e:
print("ValueError:", e)items.index('pen') : 0
items.index('pen', 2) : 3
items.count('pen') : 2
'eraser' in items : True
'marker' in items : False
ValueError: list.index(x): x not in listindex(x)returns the position of the firstx, scanning left to right; the optional second argument is a start index. Missing →ValueError.count(x)counts occurrences;intests membership.- All three are O(n) — they scan the list. On a million items that's a real cost; Part 6 shows what a
setdoes instead.
2.5 Copying lists correctly#
Recap from 1.3, now for lists specifically:
# lists_copy.py
import copy
a = [1, 2, 3]
b = a # alias: same object
c = a[:] # new list, same items (a "shallow" copy)
d = list(a) # same thing, another spelling
e = copy.copy(a) # same thing again, via the copy module
b.append(99)
print("a:", a) # changed: b is a
c.append(88)
print("a:", a, "c:", c) # a unchanged: c is a real copy
# Shallow copies share NESTED objects — appending to an inner list leaks
nested = [[1, 2], [3, 4]]
shallow = nested[:]
shallow[0].append(9)
print("nested :", nested)
print("shallow:", shallow) # both changed: the inner lists are shared
deep = copy.deepcopy(nested)
deep[0].append(10)
print("nested :", nested)
print("deep :", deep) # deep is fully independenta: [1, 2, 3, 99]
a: [1, 2, 3, 99] c: [1, 2, 3, 88]
nested : [[1, 2, 9], [3, 4]]
shallow: [[1, 2, 9], [3, 4]]
nested : [[1, 2, 9], [3, 4]]
deep : [[1, 2, 9, 10], [3, 4]]Read it line by line: b.append(99) shows up in a (alias). c.append(88) doesn't touch a — but shallow[0].append(9) does appear in nested, because the inner lists are shared. Only deepcopy is fully independent.
| You want | Write |
|---|---|
| Another name for the same list | b = a |
| Independent flat copy | a[:], a.copy(), list(a), copy.copy(a) |
| Independent copy including nested lists/dicts | copy.deepcopy(a) |
| A reversed copy | a[::-1] |
2.6 Nested lists and the two iteration traps#
Trap 1: [[0] * 3] * 3 makes three names for the same row.
# nested_lists.py
grid = [[0] * 3] * 3 # [row] * 3 copies the REFERENCE 3 times
grid[0][0] = 1 # "row 0, col 0" — but every row IS row 0
print("buggy grid:")
for row in grid:
print(" ", row)
grid_ok = [[0] * 3 for _ in range(3)] # a NEW inner list per row
grid_ok[0][0] = 1
print("fixed grid:")
for row in grid_ok:
print(" ", row)buggy grid:
[1, 0, 0]
[1, 0, 0]
[1, 0, 0]
fixed grid:
[1, 0, 0]
[0, 0, 0]
[0, 0, 0][x] * n repeats the reference to x, not a copy of it — fine for immutable x (ints, strings), catastrophic for mutable ones. The fix is a comprehension that calls the constructor once per row. Comprehensions get their own lesson in 01A.5; for now read [[0] * 3 for _ in range(3)] as "build 3 separate rows of 3 zeros".
Trap 2: removing items while iterating skips elements.
# mutate_while_iterating.py
nums = [1, 2, 3, 4]
for x in nums:
if x % 2 == 0:
nums.remove(x) # the list shifts left under the iterator
print("after removing evens in-place:", nums)
nums = [1, 2, 3, 4]
kept = [x for x in nums if x % 2 != 0]
print("kept odds:", kept)
nums = [1, 2, 3, 4]
for x in nums[:]: # iterate over a COPY
if x % 2 == 0:
nums.remove(x)
print("removed over a copy :", nums)after removing evens in-place: [1, 3]
kept odds: [1, 3]
removed over a copy : [1, 3]The in-place version looked right here but only by accident: removing 2 shifted 3 into the slot the iterator was about to visit, so 4 was examined out of turn and 3 was skipped entirely. On other data it silently keeps items you meant to delete. Rule: never add or remove items from a list while a for loop is walking it. Build a new list, or iterate over lst[:].
2.7 Lists as stacks and queues, and deque#
A stack is last-in-first-out (LIFO); a queue is first-in-first-out (FIFO). Lists do both jobs:
# stack_queue.py
stack = []
for task in ["parse", "clean", "embed", "store"]:
stack.append(task)
print("stack after pushes:", stack)
while stack:
print(" running:", stack.pop()) # LIFO
print("stack empty:", stack)
from collections import deque
queue = deque(["job-1", "job-2", "job-3"])
queue.append("job-4") # enqueue right
print("popleft ->", queue.popleft()) # dequeue left
print("queue :", list(queue))stack after pushes: ['parse', 'clean', 'embed', 'store']
running: store
running: embed
running: clean
running: parse
stack empty: []
popleft -> job-1
queue : ['job-2', 'job-3', 'job-4']For a stack, append + pop() are both O(1) — perfect. For a queue, queue.pop(0) on a list is O(n): every dequeue shifts all remaining elements one slot left. A million-job queue would spend all its time shuffling. collections.deque ("double-ended queue") does append/pop/appendleft/popleft in O(1) from both ends — it's the right tool for job queues, buffers and sliding windows. deque(maxlen=n) even gives you a fixed-size ring buffer that drops the oldest item automatically (Exercise 13 uses it for "last N log lines").
2.8 Unpacking and star-unpacking#
Python can pour a sequence into individual names in one statement:
# unpacking.py
first, *rest = [10, 20, 30, 40]
print("first:", first, "rest:", rest)
head, *middle, tail = range(1, 6)
print("head:", head, "middle:", middle, "tail:", tail)
x, y = 1, 2
x, y = y, x # swap without a temp
print("swapped:", x, y)
def min_max(numbers):
return min(numbers), max(numbers) # "returns" a packed tuple
lo, hi = min_max([4, 1, 9, 2])
print("lo:", lo, "hi:", hi)
record = {"id": "T-7", "status": "open"}
for k, v in record.items(): # items() yields (key, value) pairs
print(f" {k} = {v}")
def greet(name, greeting):
return f"{greeting}, {name}!"
parts = ["sam", "hi"]
print(greet(*parts)) # * unpacks the list into arguments
# The star also works INSIDE displays, not just assignments and calls
letters = ["a", "b", "c"]
flat = [*letters, *["d", "e"]]
print("two lists merged:", flat)
wrapped = [0, *flat, -1]
print("wrapped :", wrapped)first: 10 rest: [20, 30, 40]
head: 1 middle: [2, 3, 4] tail: 5
swapped: 2 1
lo: 1 hi: 9
id = T-7
status = open
hi, sam!
two lists merged: ['a', 'b', 'c', 'd', 'e']
wrapped : [0, 'a', 'b', 'c', 'd', 'e', -1]Rules of the game:
- The number of plain names must match the number of items unless a
*nameabsorbs the leftovers into a list.first, *restworks on any length ≥ 1;head, *middle, tailneeds ≥ 2. - Too many/few items without a star →
ValueError: too many values to unpack (expected N). - Unpacking works on any iterable: lists, tuples, strings (
a, b = "hi"), dict keys,range, file lines. *argsat a call site spreads a list/tuple into positional arguments;**kwargsdoes the same for dicts into keyword arguments (01A.3 covers both in the function-signature context).- The star also works inside displays, not only in assignments and calls:
[*a, *b]concatenates into a new list,[0, *xs, -1]wraps items inline, and{**d1, **d2}/{"k": v, **extra}do the same for dict literals (4.3 covers dict merges). - A function "returning two values" is really returning a tuple that the caller unpacks — there's no multi-value return type, and that's a feature:
lo, hi = min_max(xs)reads beautifully.
2.9 Lists vs arrays: when a list isn't the right container#
A Python list stores pointers to objects — each int is a full object. For a million distinct ints that's roughly 36 MB on 64-bit CPython (8 bytes per pointer plus about 28 bytes per int object). Two lighter options exist:
array.array(standard library): stores raw C values of one type —array("i", scores)uses 4 bytes per int instead of a pointer plus object. Smaller and faster for big numeric data, but only holds numbers (or bytes), and element access returns Python numbers.- NumPy arrays: the real answer for numeric/ML work — contiguous typed memory, vectorised operations, the basis of embeddings. Module 01B.11 covers it; until then, know that "array" in AI code almost always means NumPy, not
array.array.
# array_demo.py
from array import array
scores_list = [10, 20, 30, 40]
scores_arr = array("i", scores_list)
print("list :", scores_list, type(scores_list).__name__)
print("array:", scores_arr, type(scores_arr).__name__)
print("itemsize (bytes per element):", scores_arr.itemsize)list : [10, 20, 30, 40] list
array: array('i', [10, 20, 30, 40]) array
itemsize (bytes per element): 4For text, records and mixed data — which is most AI plumbing — a plain list (of dicts, mostly) remains the right choice. Reach for array/NumPy when you're doing math on millions of numbers.
Part 3: Tuples#
A tuple is an ordered, immutable sequence. It looks like a list but can't be changed after creation — which is exactly what makes it usable as a dict key, safe to share, and honest about "these values belong together".
3.1 Creating, packing and unpacking — and the (x,) trap#
# tuples_basics.py
point = (3, 4)
x, y = point
print("point:", point, "-> x:", x, "y:", y)
single = (42,) # the comma makes it a tuple
print("single:", single, type(single).__name__)
pair = 1, 2 # parentheses optional when packing
print("pair:", pair, type(pair).__name__)
# The familiar sequence operations work as expected
print("concat :", point + (5, 6))
print("repeat :", (0,) * 3)
print("in :", 4 in point, "| index:", point.index(4), "| count:", point.count(0))point: (3, 4) -> x: 3 y: 4
single: (42,) tuple
pair: (1, 2) tuple
concat : (3, 4, 5, 6)
repeat : (0, 0, 0)
in : True | index: 1 | count: 0The classic beginner trap: (42) is not a tuple — it's just 42 in parentheses, an int. The trailing comma is what makes a one-element tuple. (42,) has length 1; (42) has no length at all (it's an int).
Beyond packing, the everyday sequence operations all work on tuples: t1 + t2 concatenates, t * n repeats, x in t tests membership, and t.index(x)/t.count(x) find the first match and count occurrences — all O(n) scans, since a tuple has no hash-based lookup the way a set or dict does. ((0,) * 3 → (0, 0, 0) — the comma again.)
Tuples pack and unpack exactly like lists (2.8): a, b = pair, first, *rest = point, and a function's return a, b is packing. Anywhere a list would do for read-only iteration, a tuple signals "fixed shape".
3.2 Immutability is shallow#
A tuple can't be resized or have elements reassigned — but the objects inside can still be mutable:
# tuple_shallow.py
holder = ([1, 2], "label")
holder[0].append(3) # the LIST inside changed!
print("holder:", holder)
try:
holder[1] = "new"
except TypeError as e:
print("TypeError:", e)holder: ([1, 2, 3], 'label')
TypeError: 'tuple' object does not support item assignmentThe tuple itself is frozen — you can't swap "label" for "new" — but it never promised anything about the list it holds. This is the same shallow/deep distinction as 1.3, and it's why a tuple of dicts is not hashable: the dicts inside could change.
3.3 Tuples as records, keys and return values — vs namedtuple and dataclass#
Tuples shine in three roles:
- Records:
(x, y)coordinates,(name, score)pairs,("T-1042", "open", "high")— a fixed-shape bundle. - Dictionary keys: immutable + hashable, so
{(1, 2): "cell", (3, 4): "other"}works — a composite key without a nested dict. - Multi-value returns:
return min(xs), max(xs)packs a tuple the caller unpacks.
# tuples_keys.py
lookup = {(1, 2): "grid cell", (3, 4): "other cell"}
print(lookup[(1, 2)])
from collections import namedtuple
Ticket = namedtuple("Ticket", ["id", "status", "priority"])
t = Ticket("T-1", "open", "high")
print("t.id :", t.id) # named fields...
print("t[0] :", t[0]) # ...but still a plain tuple underneath
print("as dict :", t._asdict())grid cell
t.id : T-1
t[0] : T-1
as dict : {'id': 'T-1', 'status': 'open', 'priority': 'high'}A namedtuple is a tuple with field names — readable (t.id instead of t[0]), still indexable, unpackable and hashable, and lighter than a class. But it's still positional and still shallow-immutable.
Part 4: Dictionaries#
If lists are the workhorse, dicts are the engine. Every JSON object your code will ever parse is a dict; every API response, config file, metadata record and message payload in the AI path is dict-shaped. This is the longest part of the lesson because dicts carry the most responsibility.
4.1 Creating and reading#
# dict_basics.py
ticket = {"id": "T-1001", "status": "open", "priority": "high"}
print("ticket['id'] :", ticket["id"])
print("ticket.get('missing') :", ticket.get("missing"))
print("ticket.get('missing','n/a'):", ticket.get("missing", "n/a"))
# setdefault: insert a default ONLY if the key is absent
ticket.setdefault("assignee", "unassigned")
ticket.setdefault("assignee", "someone-else") # exists: no-op
print("ticket:", ticket)ticket['id'] : T-1001
ticket.get('missing') : None
ticket.get('missing','n/a'): n/a
ticket: {'id': 'T-1001', 'status': 'open', 'priority': 'high', 'assignee': 'unassigned'}The three access patterns, and when each is right:
| Pattern | Missing key behaviour | Use when |
|---|---|---|
d[key] |
raises KeyError |
the key must exist; absence is a bug you want loud |
d.get(key, default) |
returns default (or None) |
the key may be absent and None/fallback is meaningful |
d.setdefault(key, default) |
inserts default, returns it |
"give me the value, creating a default if needed" — the counting/grouping idiom |
>>> ticket = {"id": "T-1"}
>>> ticket["status"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
KeyError: 'status'4.2 Insertion order, iteration and views#
Since Python 3.7, dicts are guaranteed to iterate in insertion order — the order keys were first added. (CPython 3.6 had it as an implementation detail; it became language spec in 3.7.) This is why json.dumps(d) preserves your field order and why dict replaced OrderedDict for almost every use.
# dict_order_iter.py
d = {}
d["zeta"] = 1
d["alpha"] = 2
d["mid"] = 3
print("iteration order:", list(d)) # ['zeta', 'alpha', 'mid'] — NOT sorted!
print("sorted(d) keys only:", sorted(d))
print("by value, desc :", sorted(d.items(), key=lambda kv: kv[1], reverse=True))
ticket = {"id": "T-1", "status": "open", "priority": "high"}
print("keys() view :", ticket.keys())
print("values() view:", ticket.values())
print("items() view :", ticket.items())
for k, v in ticket.items():
print(f" {k} = {v}")
print("'id' in ticket :", "id" in ticket) # tests KEYS
print("'open' in ticket :", "open" in ticket) # NOT values!
print("'open' in ticket.values():", "open" in ticket.values())
# Views are LIVE — they reflect later changes
keys = ticket.keys()
ticket["assignee"] = "sam"
print("keys view after adding 'assignee':", list(keys))
print("keys() & {'id','status'}:", sorted(ticket.keys() & {"id", "status"}))iteration order: ['zeta', 'alpha', 'mid']
sorted(d) keys only: ['alpha', 'mid', 'zeta']
by value, desc : [('mid', 3), ('alpha', 2), ('zeta', 1)]
keys() view : dict_keys(['id', 'status', 'priority'])
values() view: dict_values(['T-1', 'open', 'high'])
items() view : dict_items([('id', 'T-1'), ('status', 'open'), ('priority', 'high')])
id = T-1
status = open
priority = high
'id' in ticket : True
'open' in ticket : False
'open' in ticket.values(): True
keys view after adding 'assignee': ['id', 'status', 'priority', 'assignee']
keys() & {'id','status'}: ['id', 'status']Points that trip people up:
- Iterating a dict yields keys, not items.
for k in dgives keys;for k, v in d.items()gives pairs;d.values()gives values. Forgetting.items()is the #1 beginner bug. intests keys only.'open' in ticketisFalseeven though"open"is a value — usein d.values()(O(n) scan) or restructure.keys()/values()/items()are live views, not copies — they see later mutations.keys()supports set operations (&,|,-) against a set of keys, anditems()against a set of(key, value)pairs —ticket.items() & {("id", "T-1")}finds the pair, whileticket.items() & {"id"}silently returns an empty set because"id"isn't a pair.- Insertion order ≠ sorted order. If you need sorted output,
sorted(d)sorts the keys andsorted(d.items(), key=lambda kv: kv[1], reverse=True)sorts by value (as shown above) — never assume iteration gives sorted order.
4.3 Changing a dict: update, |, |=, deletion#
# dict_mutate.py
ticket = {"id": "T-1001", "status": "open", "priority": "high"}
ticket["status"] = "in-progress" # assign existing key
ticket["assignee"] = "sam" # assign new key
print("ticket:", ticket)
# update() merges another dict (or iterable of pairs); right side wins
patch = {"priority": "urgent", "tags": ["vip"]}
ticket.update(patch)
print("after update:", ticket)
# | creates a NEW dict; |= merges in place
base = {"a": 1, "b": 2}
extra = {"b": 20, "c": 30}
print("base | extra :", base | extra)
print("base :", base) # unchanged
base |= extra
print("after |= :", base)
# {**a, **b} display-unpack merge — also works inline inside a literal
combined = {"env": "prod", **base, **extra, "region": "eu"}
print("display-unpack:", combined)
# deleting
del ticket["tags"]
print("pop('assignee'):", ticket.pop("assignee"))
print("popitem() :", ticket.popitem()) # removes LAST inserted pair
print("pop missing, default:", ticket.pop("nonexistent", "fallback"))
print("ticket :", ticket)
ticket.clear()
print("after clear :", ticket)ticket: {'id': 'T-1001', 'status': 'in-progress', 'priority': 'high', 'assignee': 'sam'}
after update: {'id': 'T-1001', 'status': 'in-progress', 'priority': 'urgent', 'assignee': 'sam', 'tags': ['vip']}
base | extra : {'a': 1, 'b': 20, 'c': 30}
base : {'a': 1, 'b': 2}
after |= : {'a': 1, 'b': 20, 'c': 30}
display-unpack: {'env': 'prod', 'a': 1, 'b': 20, 'c': 30, 'region': 'eu'}
pop('assignee'): sam
popitem() : ('priority', 'urgent')
pop missing, default: fallback
ticket : {'id': 'T-1001', 'status': 'in-progress'}
after clear : {}Merge semantics to internalize:
d1 | d2andd1.update(d2)— right side wins on key clashes.{"b": 2} | {"b": 20}→{"b": 20}.{**d1, **d2}is the display-unpack spelling of the same merge — it produces a new dict and, uniquely among the merge forms, works inside a literal:{"env": "prod", **overrides, "region": "eu"}. Same right-side-wins rule; keys keep their first-insertion position.|returns a new dict (shallow — nested objects still shared);|=mutates. Same shallow-copy caveat as everywhere.update()also accepts an iterable of(key, value)pairs and keyword args:d.update([("x", 1)], y=2).pop(key)removes and returns;pop(key, default)returns the default instead of raisingKeyErrorwhen the key is absent — reach for it when a missing key is routine;popitem()removes the last-inserted pair (LIFO, since 3.7);del d[key]removes without returning;clear()empties.
4.4 Hashability: what can be a key#
A dict key (or set member) must be hashable: the object must have a hash value that never changes during its life, and equality must agree with it. In plain terms: immutable objects are hashable; mutable objects are not — with one famous exception family.
# dict_hashable.py
d = {}
d["plain-string"] = "ok"
d[42] = "ok"
d[3.14] = "ok"
d[(1, 2)] = "tuple of immutables: ok"
d[frozenset(["a", "b"])] = "frozenset: ok"
print("hashable keys work:", len(d), "entries")
# True and 1 are the SAME key: bool is a subclass of int
d[1] = "one"
d[True] = "bool overwrote it"
print("d[1] after d[True]:", d[1])
# Unhashable objects cannot be keys — lists, dicts, sets
for bad in ([1, 2], {"a": 1}, {"x", "y"}):
try:
d[bad] = "nope"
except TypeError as e:
print(type(bad).__name__, "->", e)
# A tuple containing a list is unhashable too — hashability is recursive
t = ([1, 2], "x")
try:
d[t] = "nope"
except TypeError as e:
print("tuple-with-list ->", e)
# frozenset CAN be a dict key / set member where set cannot
s = {frozenset(["a", "b"]), frozenset(["c"])}
print("set of frozensets:", sorted(map(sorted, s)))hashable keys work: 5 entries
d[1] after d[True]: bool overwrote it
list -> cannot use 'list' as a dict key (unhashable type: 'list')
dict -> cannot use 'dict' as a dict key (unhashable type: 'dict')
set -> cannot use 'set' as a dict key (unhashable type: 'set')
tuple-with-list -> cannot use 'tuple' as a dict key (unhashable type: 'list')
set of frozensets: [['a', 'b'], ['c']]The rules, precisely:
| Hashable (can be keys/members) | Unhashable (cannot) |
|---|---|
str, int, float, bool, None |
list, dict, set, bytearray |
tuple of hashables only |
tuple containing any unhashable |
frozenset |
— |
(user classes, unless they define __eq__ without __hash__) |
most custom objects after __eq__ |
Two subtleties worth internalizing:
True == 1andhash(True) == hash(1)— they are literally the same dict key.d[1] = "one"; d[True] = "x"overwrites. Same trap with0/Falseand1.0/True. Rarely bites, but it's why "is this key already there?" can surprise you.- Hashability is recursive:
(1, [2])is a tuple, but the list inside makes the whole tuple unhashable.frozensetis the immutable set — hashable, usable as a key or member of another set.
4.5 Nested dicts and safe traversal#
API responses nest dicts inside lists inside dicts. Reaching response["choices"][0]["message"]["content"] assumes a shape that real data doesn't always have — a missing key or an empty list crashes the whole pipeline:
# nested_getpath.py
response = {
"id": "chatcmpl-123",
"choices": [
{"index": 0, "message": {"role": "assistant", "content": "Hello!"}}
],
"usage": {"prompt_tokens": 12, "completion_tokens": 5},
}
# Naive access assumes the shape is always the same — it isn't.
try:
print(response["choices"][0]["message"]["tool_calls"][0]["name"])
except (KeyError, IndexError, TypeError) as e:
print("naive access fails:", type(e).__name__, "-", e)
# get_path(): walk a path mixing dict keys and list indexes,
# returning a default whenever any step can't be taken.
def get_path(obj, path, default=None):
cur = obj
for key in path:
if isinstance(cur, dict) and key in cur:
cur = cur[key]
elif isinstance(cur, list) and isinstance(key, int) and 0 <= key < len(cur):
cur = cur[key]
else:
return default
return cur
print(get_path(response, ["choices", 0, "message", "content"]))
print(get_path(response, ["choices", 0, "message", "tool_calls", 0, "name"], "none"))
print(get_path(response, ["usage", "total_tokens"], 0))
print(get_path(response, ["choices", 5, "message"], "out of range"))naive access fails: KeyError - 'tool_calls'
Hello!
none
0
out of rangeRead the get_path loop once and it never needs reading again: each key in path is either a dict key or a list index; if the current object can't supply it, return default immediately. This one helper will appear in your toolkit forever — stream parsers, webhook handlers and report builders all need "dig here if the shape allows, else fallback". Build it step by step as shown: dict-only first, then add list support — the final version is barely longer.
4.6 Lists of dicts: the shape of records#
Here is the running example for the rest of the module — support tickets exactly as an API or database would hand them to you: a list of dicts, each dict a record with the same keys:
# ticket_records.py
from collections import Counter, defaultdict
TICKETS = [
{"id": "T-1042", "subject": "Cannot log in after password reset",
"category": "account", "priority": "high", "status": "open",
"created": "2026-10-28"},
{"id": "T-1043", "subject": "Invoice total looks wrong",
"category": "billing", "priority": "medium", "status": "open",
"created": "2026-10-29"},
{"id": "T-1044", "subject": "Export to CSV is empty",
"category": "bug", "priority": "urgent", "status": "in-progress",
"created": "2026-10-30"},
{"id": "T-1045", "subject": "Add dark mode to settings",
"category": "feature", "priority": "low", "status": "open",
"created": "2026-10-30"},
{"id": "T-1046", "subject": "SSO login fails for one domain",
"category": "account", "priority": "high", "status": "resolved",
"created": "2026-10-31"},
{"id": "T-1047", "subject": "Duplicate charge on card",
"category": "billing", "priority": "urgent", "status": "open",
"created": "2026-11-01"},
{"id": "T-1044", "subject": "Export to CSV is empty (re-filed)",
"category": "bug", "priority": "urgent", "status": "open",
"created": "2026-11-02"}, # same id as T-1044: a duplicate record
{"id": "T-1048", "subject": "Webhook retries look wrong",
"category": "bug", "priority": "medium", "status": "closed",
"created": "2026-11-02"},
]
# 1. Filter — a list comprehension (preview of 01A.5)
open_tickets = [t for t in TICKETS if t["status"] == "open"]
print("open tickets:", [t["id"] for t in open_tickets])
# 2. Group by a field — defaultdict(list)
by_status = defaultdict(list)
for t in TICKETS:
by_status[t["status"]].append(t["id"])
print("by status:", dict(by_status))
# 3. Count by a field — Counter
counts = Counter(t["category"] for t in TICKETS)
print("by category:", counts.most_common())
# 4. Sort by a field — urgent first, then oldest first
rank = {"low": 0, "medium": 1, "high": 2, "urgent": 3}
ordered = sorted(TICKETS, key=lambda t: (-rank[t["priority"]], t["created"]))
print("top 3 by priority:", [t["id"] for t in ordered[:3]])
# 5. Build an index by id — dict comprehension (preview)
by_id = {t["id"]: t for t in TICKETS}
print("T-1047 subject:", by_id["T-1047"]["subject"])
# 6. Find duplicates — T-1044 appears twice
seen = set()
dupes = []
for t in TICKETS:
if t["id"] in seen:
dupes.append(t["id"])
seen.add(t["id"])
print("duplicate ids:", dupes)open tickets: ['T-1042', 'T-1043', 'T-1045', 'T-1047', 'T-1044']
by status: {'open': ['T-1042', 'T-1043', 'T-1045', 'T-1047', 'T-1044'], 'in-progress': ['T-1044'], 'resolved': ['T-1046'], 'closed': ['T-1048']}
by category: [('bug', 3), ('account', 2), ('billing', 2), ('feature', 1)]
top 3 by priority: ['T-1044', 'T-1047', 'T-1044']
T-1047 subject: Duplicate charge on card
duplicate ids: ['T-1044']Six recipes, all built from this lesson's pieces:
| Recipe | Tool | Note |
|---|---|---|
| Filter records | [t for t in TICKETS if cond] |
comprehension — 01A.5 owns them fully |
| Group by field | defaultdict(list) + loop |
groups keep first-seen order |
| Count by field | Counter(...) |
.most_common(n) for top-N |
| Sort by field(s) | sorted(..., key=lambda) |
tuple key for multi-field (2.3) |
| Index by id | {t["id"]: t for t in TICKETS} |
dict comprehension — O(1) lookup later |
| Find duplicates | set for seen + list for dupes |
set membership is O(1) |
This list-of-dicts shape is the data shape of the whole path: message lists in 03.2, tool-call payloads in 03.5, metadata records in 05.8, stream events in 03.3.
4.7 dict comprehension preview, and zip/dict(zip(...))#
Comprehensions get a full lesson in 01A.5; you've now seen two ([t for t in ...], {t["id"]: t for t in ...}). The dict form {key_expr: value_expr for item in iterable} builds a dict in one pass — reach for it whenever you'd write d = {}; for ...: d[k] = v.
zip pairs items from parallel sequences position-by-position; dict(zip(keys, values)) builds a dict from two lists — the classic "columns to record" move:
# zip_demo.py
ids = ["T-1042", "T-1043", "T-1044"]
statuses = ["open", "closed", "open"]
status_by_id = dict(zip(ids, statuses))
print("dict(zip(...)):", status_by_id)
# zip stops at the SHORTEST input — silent truncation
print("zip unequal lengths:", list(zip(ids, statuses, ["extra"])))
# strict=True (Python 3.10+) makes unequal lengths an error instead
try:
list(zip(ids, statuses, ["x"], strict=True))
except ValueError as e:
print("strict=True ->", e)dict(zip(...)): {'T-1042': 'open', 'T-1043': 'closed', 'T-1044': 'open'}
zip unequal lengths: [('T-1042', 'open', 'extra')]
strict=True -> zip() argument 3 is shorter than arguments 1-24.8 defaultdict, Counter, OrderedDict and ChainMap#
The collections module (toured fully in 01A.7) ships four dict-flavoured helpers you'll meet constantly:
# collections_helpers.py
from collections import ChainMap, Counter, OrderedDict, defaultdict
# defaultdict(int): missing keys start at 0 — no setdefault needed
word_counts = defaultdict(int)
for word in "a b a c b a d c a".split():
word_counts[word] += 1
print("word_counts:", dict(word_counts))
print("missing 'z' now:", word_counts["z"]) # auto-created as 0
# Counter: a dict specialised for counting hashable items
votes = Counter(["approve", "reject", "approve", "approve", "reject", "maybe"])
print("votes :", dict(votes))
print("most_common(2) :", votes.most_common(2))
print("total votes :", sum(votes.values()))
# OrderedDict: regular dicts keep insertion order since 3.7,
# so OrderedDict is mostly legacy — but move_to_end() is still handy.
od = OrderedDict([("a", 1), ("b", 2), ("c", 3)])
od.move_to_end("a")
print("after move_to_end:", list(od))
# ChainMap: layered lookups — first mapping wins, writes go to the first
defaults = {"theme": "light", "lang": "en", "page_size": 20}
user_prefs = {"theme": "dark"}
prefs = ChainMap(user_prefs, defaults)
print("theme:", prefs["theme"], "| lang:", prefs["lang"])
prefs["theme"] = "sepia" # writes into user_prefs, not defaults
print("user_prefs:", user_prefs)
print("defaults unchanged:", defaults)word_counts: {'a': 4, 'b': 2, 'c': 2, 'd': 1}
missing 'z' now: 0
votes : {'approve': 3, 'reject': 2, 'maybe': 1}
most_common(2) : [('approve', 3), ('reject', 2)]
total votes : 6
after move_to_end: ['b', 'c', 'a']
theme: dark | lang: en
user_prefs: {'theme': 'sepia'}
defaults unchanged: {'theme': 'light', 'lang': 'en', 'page_size': 20}| Helper | What it is | Reach for it when |
|---|---|---|
defaultdict(factory) |
dict that auto-creates missing keys via factory() (int, list, set, dict) |
counting, grouping, "append to bucket" loops |
Counter |
dict of counts with .most_common(), +/-/&/| between counters |
frequencies, top-N, multiset math |
OrderedDict |
dict with guaranteed order + move_to_end |
LRU caches; otherwise plain dict suffices (3.7+) |
ChainMap |
stack of dicts; lookup falls through, writes hit the first | layered config: defaults ← user ← overrides |
4.9 JSON-compatible shapes#
When your dicts cross a JSON boundary — json.dumps/loads, an API request, a file — three silent transformations happen:
# json_shape.py
import json
record = {
"id": "T-1",
"tags": ("urgent", "billing"), # tuple
"meta": {1: "one", 2: "two"}, # int keys
"ok": True,
}
text = json.dumps(record)
print("json.dumps :", text)
back = json.loads(text)
print("back :", back)
print("tags type :", type(back["tags"]).__name__)
print("meta keys :", list(back["meta"]))json.dumps : {"id": "T-1", "tags": ["urgent", "billing"], "meta": {"1": "one", "2": "two"}, "ok": true}
back : {'id': 'T-1', 'tags': ['urgent', 'billing'], 'meta': {'1': 'one', '2': 'two'}, 'ok': True}
tags type : list
meta keys : ['1', '2']- Tuples become lists — JSON has no tuple type. Round-tripping changes the type; code that checks
isinstance(x, tuple)breaks after a JSON hop. - Non-string dict keys become strings —
{1: "x"}→{"1": "x"}.Truebecomes"true". Int-keyed dicts don't survive JSON. NaN/Infinityaren't valid JSON but Python'sjsonmodule emits them by default (allow_nan=True) — an interoperability trap 01A.9 covers properly.- Everything else — nested dicts, lists, strings, numbers, booleans,
None— round-trips cleanly. The safe shape for anything crossing JSON: dicts with string keys, lists, and scalars. Build your records that way and serialization is boring.
Part 5: Sets and frozenset#
A set is an unordered collection of unique, hashable items. No positions, no duplicates, no guaranteed iteration order — which is exactly why membership tests are O(1): the hash does the work, not a scan.
5.1 Creation, membership and deduplication#
# sets_basics.py
tags = {"python", "api", "llm"} # set literal
tags.add("rag")
tags.add("api") # already there: no-op
print("tags:", sorted(tags)) # sort for display — set order is arbitrary
ids = ["t-3", "t-1", "t-2", "t-1", "t-3", "t-4"]
print("deduped + sorted :", sorted(set(ids)))
print("order-preserving :", list(dict.fromkeys(ids)))
# dict.fromkeys(seq, default): a lookup table in one call — but the
# default object is SHARED by every key (the mutable-default trap again!)
counts = dict.fromkeys(["alpha", "beta", "gamma"], 0)
print("fromkeys default :", counts)
buckets = dict.fromkeys(["x", "y"], [])
buckets["x"].append(1)
print("shared default trap :", buckets) # 'y' sees it too — same list object
# frozenset: immutable set — usable as a dict key or set member
pair = frozenset(["a", "b"])
lookup = {pair: "the a-b pair"}
print("frozenset lookup :", lookup[frozenset(["b", "a"])])
print("frozenset | frozenset:", sorted(pair | frozenset(["c"])))
try:
pair.add("z")
except AttributeError as e:
print("frozenset.add ->", type(e).__name__, "-", e)tags: ['api', 'llm', 'python', 'rag']
deduped + sorted : ['t-1', 't-2', 't-3', 't-4']
order-preserving : ['t-3', 't-1', 't-2', 't-4']
fromkeys default : {'alpha': 0, 'beta': 0, 'gamma': 0}
shared default trap : {'x': [1], 'y': [1]}
frozenset lookup : the a-b pair
frozenset | frozenset: ['a', 'b', 'c']
frozenset.add -> AttributeError - 'frozenset' object has no attribute 'add'The two dedupe idioms side by side:
set(ids)— fastest, but loses order and duplicates by design. Fine when order doesn't matter; sort or re-derive order when it does.dict.fromkeys(ids)— keeps first-seen order (dicts are insertion-ordered), still O(n), still dedupes. The order-preserving dedupe of choice. Its two-argument formdict.fromkeys(keys, 0)builds a lookup table in one call — but every key shares the same default object, sodict.fromkeys(keys, [])gives all keys one list: append through"x"and"y"sees it too.- Membership
'x' in some_setis O(1) vs O(n) for a list — the single most common reason to reach for a set (Part 6 quantifies it).
5.2 Set algebra and subset tests#
# set_algebra.py
tags_a = {"python", "api", "llm"}
tags_b = {"api", "rag", "python"}
print("union :", sorted(tags_a | tags_b)) # in either
print("intersection :", sorted(tags_a & tags_b)) # in both
print("difference a - b :", sorted(tags_a - tags_b)) # in a only
print("symmetric difference:", sorted(tags_a ^ tags_b)) # in exactly one
print("a <= b (subset) :", tags_a <= tags_b)
print("b >= a (superset) :", tags_b >= tags_a)
print("proper subset < :", {"python", "api"} < tags_b)
print("equal sets, <= :", tags_a <= {"api", "llm", "python"})
print("isdisjoint :", tags_a.isdisjoint({"x", "y"}))
# Operators need BOTH sides to be sets; methods accept any iterable
try:
tags_a | ["x", "y"]
except TypeError as e:
print("a | [list] ->", e)
print("a.union(iterable) :", sorted(tags_a.union(["x", "y"])))
print("a.intersection(list):", sorted(tags_a.intersection(["api", "db"])))union : ['api', 'llm', 'python', 'rag']
intersection : ['api', 'python']
difference a - b : ['llm']
symmetric difference: ['llm', 'rag']
a <= b (subset) : False
b >= a (superset) : False
proper subset < : True
equal sets, <= : True
isdisjoint : True
a | [list] -> unsupported operand type(s) for |: 'set' and 'list'
a.union(iterable) : ['api', 'llm', 'python', 'x', 'y']
a.intersection(list): ['api']| Operator | Method | Meaning |
|---|---|---|
a | b |
a.union(b) |
in a or b (or both) |
a & b |
a.intersection(b) |
in both |
a - b |
a.difference(b) |
in a, not b |
a ^ b |
a.symmetric_difference(b) |
in exactly one |
a <= b |
a.issubset(b) |
every element of a is in b (equal sets count) |
a >= b |
a.issuperset(b) |
every element of b is in a |
a < b |
— | proper subset: <= and the sets differ |
a > b |
— | proper superset: >= and the sets differ |
| — | a.isdisjoint(b) |
no element in common (True/False, not a set) |
Real uses in the AI path: "which expected webhook event types never arrived" (expected - received), "which model ids are allowed AND requested" (allowed & requested), "tags shared by two documents" (tags_a & tags_b for relatedness), "dedupe before embedding" (set(texts)).
5.3 Mutating sets: add, remove vs discard, update, in-place operators#
Sets change through methods and augmented assignment — the same in-place vs new-object discipline as lists and dicts:
# sets_mutate.py
tags = {"python", "api", "llm"}
tags.update(["rag", "eval", "api"]) # bulk-add; duplicates ignored
print("after update:", sorted(tags))
try:
tags.remove("does-not-exist") # KeyError, like d[missing_key]
except KeyError as e:
print("remove missing ->", type(e).__name__)
tags.discard("does-not-exist") # silent no-op — the safe form
tags.discard("eval")
print("after discards:", sorted(tags))
tags -= {"rag"} # in-place difference
tags |= {"agents", "eval"} # in-place union
print("after -= and |=:", sorted(tags))
tags &= {"python", "api", "llm"} # keep only these
tags ^= {"python"} # toggle membership
print("after &= and ^=:", sorted(tags))
probe = {"a", "b", "c"}
probe.pop() # removes an ARBITRARY element
print("size after pop:", len(probe), "— which one went is arbitrary")
print("isdisjoint:", probe.isdisjoint({"x", "y"}))
probe.clear()
print("after clear:", probe)after update: ['api', 'eval', 'llm', 'python', 'rag']
remove missing -> KeyError
after discards: ['api', 'llm', 'python', 'rag']
after -= and |=: ['agents', 'api', 'eval', 'llm', 'python']
after &= and ^=: ['api', 'llm']
size after pop: 2 — which one went is arbitrary
isdisjoint: True
after clear: set()The details that matter:
remove(x)raisesKeyErrorwhenxis absent;discard(x)silently does nothing. Same trap family aslist.removeandd[key]— pick deliberately:removewhen absence signals a bug,discardwhen "make sure it's gone" is the intent.update(iterable)bulk-adds and, like the non-operator methods, accepts any iterable. The in-place operators|=,&=,-=,^=mirror|,&,-,^but mutate — and like the plain operators they require set operands:tags |= ["x"]is aTypeErrorwheretags.update(["x"])works.pop()removes an arbitrary element — there is no "first" in an unordered set, so never rely on which one you get (if you need order, that's a list's job).clear()empties the set but keeps the object, likelist.clear().- The in-place forms mutate like
list.sort()— writes = s | t(ors = s.union(t)) when you want a new set instead.
Part 6: Choosing a structure#
6.1 Big-O in plain English#
Big-O describes how an operation's cost grows with input size n. You don't need the math — just these landmarks:
- O(1) — "instant": cost doesn't grow with
n. Dict/set lookup by key. - O(log n) — "doubling
nadds one step": binary search on sorted data. - O(n) — "proportional": scanning every item once. List membership,
list.index, building a list from a generator. - O(n log n) — "sorting":
sorted,list.sort. - O(n²) — "every item meets every item": nested loops over the same data — the thing to avoid at scale.
6.2 The cost table#
| Operation | list |
tuple |
dict |
set |
deque |
|---|---|---|---|---|---|
Index by position x[i] |
O(1) | O(1) | — | — | O(1) ends |
Lookup by key/value x in c / c[k] |
O(n) | O(n) | O(1) | O(1) | O(n) |
| Append at end | O(1) amortised* | — (immutable) | — | — | O(1) |
| Insert/remove at front | O(n) | — | — | — | O(1) |
| Insert/remove anywhere | O(n) | — | O(1) avg | O(1) avg | O(n) middle |
| Sort | O(n log n) | O(n log n) via sorted |
— | — | — |
| Preserve order | yes | yes | yes (3.7+) | no | yes |
| Allow duplicates | yes | yes | keys unique | no | yes |
| Mutable | yes | no | yes | yes | yes |
* Amortised O(1): occasionally appending forces the list to grow and copy everything — rare enough that the average is constant.
A real (but machine-dependent) demonstration — run it yourself:
# membership_timing.py — why `in` is O(n) on a list but ~O(1) on set/dict.
# Run: python3 membership_timing.py — the microseconds vary by machine.
import timeit
n = 100_000
haystack_list = list(range(n))
haystack_set = set(range(n))
haystack_dict = {i: i for i in range(n)}
needle = n - 1 # worst case for a list scan: the last element
setup = "from __main__ import haystack_list, haystack_set, haystack_dict, needle"
for name, stmt in [
("list scan (needle in list)", "needle in haystack_list"),
("set lookup (needle in set) ", "needle in haystack_set"),
("dict lookup (needle in dict)", "needle in haystack_dict"),
]:
t = timeit.timeit(stmt, setup=setup, number=20) / 20
print(f"{name}: {t * 1e6:10.2f} us ({t:.6f} s)")list scan (needle in list): 497.46 us (0.000497 s)
set lookup (needle in set) : 0.12 us (0.000000 s)
dict lookup (needle in dict): 0.03 us (0.000000 s)Searching for the last element of a 100,000-item list scans all 100k pointers; the set and dict hash straight to the bucket. The ratio grows with n — that's the whole argument for "index first, scan never". The lesson ran this on Python 3.14.6; your microseconds will differ, the ordering won't.
6.3 The decision table#
| You need... | Use | Because |
|---|---|---|
| Ordered items, change often, index by position | list |
O(1) indexing, O(1) append |
| Fixed-shape bundle, hashable, "return two values" | tuple |
immutable → safe keys, cheap |
| Key→value lookup, JSON-shaped records | dict |
O(1) by key, ordered, JSON-native |
| Unique items, fast membership, set math | set |
O(1) in, algebra operators |
| Immutable set (as a key/member) | frozenset |
hashable |
| FIFO queue / LIFO stack at scale | deque |
O(1) both ends |
| Counting / grouping | Counter / defaultdict |
built for it |
| Sorted iteration over a set/dict | sorted(c) |
sets/dicts aren't sorted |
| Top-N without full sort | heapq.nlargest |
O(n log k) |
| Insert into sorted list | bisect.insort |
O(log n) search + O(n) shift |
| Compact numbers | array.array / NumPy |
raw C values, not pointers |
| Order-preserving dedupe | dict.fromkeys |
O(n), keeps first-seen order |
6.4 heapq, bisect and the rest of collections#
Two more stdlib tools complete the toolkit — both awareness-level here, deeper use comes with the problems that need them:
# heapq_bisect.py
import bisect
import heapq
scores = [88, 42, 97, 55, 71, 63, 55]
print("nlargest(3) :", heapq.nlargest(3, scores))
print("nsmallest(2):", heapq.nsmallest(2, scores))
heap = []
for s in scores:
heapq.heappush(heap, s)
print("heappop x3 :", [heapq.heappop(heap) for _ in range(3)])
prices = [10, 20, 30, 40, 50]
bisect.insort(prices, 35) # keeps the list sorted
print("after insort(35):", prices)
print("bisect_left (35) :", bisect.bisect_left(prices, 35))nlargest(3) : [97, 88, 71]
nsmallest(2): [42, 55]
heappop x3 : [42, 55, 55]
after insort(35): [10, 20, 30, 35, 40, 50]
bisect_left (35) : 3heapqmaintains a heap — a list arranged so the smallest item is always at index 0.heappush/heappopgive you a priority queue in O(log n);nlargest(n, xs)/nsmallestanswer "top-N" without sorting everything. For records, push(priority, item)tuples — equal priorities fall through to comparing the second element, so if the items aren't comparable (dicts!) you getTypeError; the classic fix is a third element, an incrementing counter:(priority, counter, item).bisectfinds insertion points in an already-sorted list via binary search (O(log n));insortinserts keeping order.bisect_left/insort_leftinsert before existing equal entries; the plainbisect/insortnames are aliases for the_rightvariants, which insert after them — it matters when equal keys must keep arrival order. Use it for "keep this list sorted as items arrive" — price tiers, thresholds, score cutoffs.array.arrayyou met in 2.9;collectionsgave youdeque(2.7) plusdefaultdict/Counter/OrderedDict/ChainMap/namedtuple(3.3, 4.8).itertools,functoolsand friends arrive in 01A.5 and 01A.7.
Part 7: The ticket-triage toolkit#
Deep-dive
Time to assemble. Everything in Parts 2–6 combines into the data layer the rest of Module 01A builds on — the same ticket records as 4.6, now with a customer field added and named functions around them:
# tickets.py — the support-ticket toolkit, assembled from Parts 2-6.
# Run: python3 tickets.py (standard library only, no network, no AI)
from collections import Counter, defaultdict
TICKETS = [
{"id": "T-1042", "subject": "Cannot log in after password reset",
"category": "account", "priority": "high", "status": "open",
"customer": "ana@example.com", "created": "2026-10-28"},
{"id": "T-1043", "subject": "Invoice total looks wrong",
"category": "billing", "priority": "medium", "status": "open",
"customer": "bo@example.com", "created": "2026-10-29"},
{"id": "T-1044", "subject": "Export to CSV is empty",
"category": "bug", "priority": "urgent", "status": "in-progress",
"customer": "cy@example.com", "created": "2026-10-30"},
{"id": "T-1045", "subject": "Add dark mode to settings",
"category": "feature", "priority": "low", "status": "open",
"customer": "di@example.com", "created": "2026-10-30"},
{"id": "T-1046", "subject": "SSO login fails for one domain",
"category": "account", "priority": "high", "status": "resolved",
"customer": "ana@example.com", "created": "2026-10-31"},
{"id": "T-1047", "subject": "Duplicate charge on card",
"category": "billing", "priority": "urgent", "status": "open",
"customer": "bo@example.com", "created": "2026-11-01"},
{"id": "T-1044", "subject": "Export to CSV is empty (re-filed)",
"category": "bug", "priority": "urgent", "status": "open",
"customer": "cy@example.com", "created": "2026-11-02"},
{"id": "T-1048", "subject": "Webhook retries look wrong",
"category": "bug", "priority": "medium", "status": "closed",
"customer": "di@example.com", "created": "2026-11-02"},
]
PRIORITY_RANK = {"low": 0, "medium": 1, "high": 2, "urgent": 3}
def index_by_id(tickets):
"""Build {id: ticket} for O(1) lookup. Later duplicates win."""
return {t["id"]: t for t in tickets}
def group_by(tickets, field):
"""{field_value: [tickets]} preserving first-seen order of groups."""
groups = defaultdict(list)
for t in tickets:
groups[t[field]].append(t)
return groups
def count_by(tickets, field):
return Counter(t[field] for t in tickets)
def sort_by_priority(tickets):
"""Urgent first; ties broken by oldest ticket first."""
return sorted(tickets, key=lambda t: (-PRIORITY_RANK[t["priority"]], t["created"]))
def find_duplicate_ids(tickets):
"""Ids that appear more than once, in order of second occurrence."""
seen = set()
dupes = []
for t in tickets:
if t["id"] in seen and t["id"] not in dupes:
dupes.append(t["id"])
seen.add(t["id"])
return dupes
def open_tickets(tickets):
return [t for t in tickets if t["status"] == "open"]
if __name__ == "__main__":
print(f"{len(TICKETS)} ticket records loaded")
print("open:", [t["id"] for t in open_tickets(TICKETS)])
print("by status:", {k: len(v) for k, v in group_by(TICKETS, "status").items()})
print("by category:", count_by(TICKETS, "category").most_common())
print("top 3:", [t["id"] for t in sort_by_priority(TICKETS)[:3]])
print("duplicate ids:", find_duplicate_ids(TICKETS))
print("lookup T-1047:", index_by_id(TICKETS)["T-1047"]["subject"])8 ticket records loaded
open: ['T-1042', 'T-1043', 'T-1045', 'T-1047', 'T-1044']
by status: {'open': 5, 'in-progress': 1, 'resolved': 1, 'closed': 1}
by category: [('bug', 3), ('account', 2), ('billing', 2), ('feature', 1)]
top 3: ['T-1044', 'T-1047', 'T-1044']
duplicate ids: ['T-1044']
lookup T-1047: Duplicate charge on cardEvery function is a recipe you already own: index_by_id is the dict comprehension from 4.7, group_by is defaultdict(list) from 4.6, count_by wraps Counter, sort_by_priority is the tuple-key sort from 2.3, and find_duplicate_ids is the set-membership pattern. This tickets.py is the data layer for the rest of the module: 01A.5 will stream it through generators, 01A.6 will turn each dict into a Ticket dataclass, 01A.8 will harden the loading, and 01A.9 will read and write it as CSV and JSON.
Common mistakes#
The gallery — each snippet below is real, deterministic stdlib Python:
b = a is an alias, not a copy. Both names point at the same list — appending through b shows up in a:
a = [1, 2]
b = a
b.append(3)
print(a, b, a is b)[1, 2, 3] [1, 2, 3] TrueCopies need a[:], list(a) or copy.copy; nested objects still need copy.deepcopy (§1.3). The same trap makes [[0] * 3] * 3 produce three names for one row (§2.6).
KeyError on a missing key. d[key] is the loud access — perfect when absence is a bug, fatal when it's routine:
ticket = {"id": "T-1"}
print(ticket["status"])Traceback (most recent call last):
File "l4_keyerror.py", line 2, in <module>
print(ticket["status"])
~~~~~~^^^^^^^^^^
KeyError: 'status'Pick d.get(k, default) or k in d when the key may be absent (§4.1) — and remember d.get(k) returning None can't distinguish "absent" from "present but null".
Removing items while iterating skips elements. The for loop walks the list by position; remove shifts everything left under it:
nums = [1, 2, 4, 3]
for x in nums:
if x % 2 == 0:
nums.remove(x)
print("odds only wanted [1, 3]; got:", nums)odds only wanted [1, 3]; got: [1, 4, 3]4 survived: after 2 was removed, 4 slid into the slot the iterator had already passed. Never add or remove items from a list (or keys from a dict — that raises RuntimeError: dictionary changed size during iteration) while a for loop is walking it. Build a new list or iterate over lst[:] (§2.6).
Unhashable dict keys. Keys must be immutable — a list (or dict, set, bytearray, or a tuple containing one) can't be a key because its contents can change, so it has no stable hash:
d = {}
d[[1, 2]] = "x"Traceback (most recent call last):
File "l4_unhashable.py", line 2, in <module>
d[[1, 2]] = "x"
~^^^^^^^^
TypeError: cannot use 'list' as a dict key (unhashable type: 'list')Use a tuple of hashables, a frozenset, or a string key instead (§4.4).
Assuming sets keep order. A set iterates in hash-dependent order — not insertion order, not sorted order — and the order can differ between runs:
ids = ["t-3", "t-1", "t-2", "t-1"]
print("dict.fromkeys:", list(dict.fromkeys(ids))) # first-seen order, always
print("set: ", list(set(ids))) # arbitrary order
print("sorted(set): ", sorted(set(ids)))dict.fromkeys: ['t-3', 't-1', 't-2']
set: ['t-1', 't-3', 't-2']
sorted(set): ['t-1', 't-2', 't-3'](The set: line genuinely varies between processes — string hashing is randomised per run.) Dicts, by contrast, have preserved insertion order since Python 3.7. Order-preserving dedupe is dict.fromkeys; sorted output is sorted(set(...)) (§5.1, §4.2).
Common misconceptions#
| Misconception | Reality |
|---|---|
"b = a copies the list." |
It binds a second name to the same object. Copies need a[:], list(a) or copy.copy/deepcopy (1.3). |
| "Tuples are immutable, so everything inside is frozen." | Immutability is shallow: a tuple holding a list still allows t[0].append(x) (3.2). |
"(42) is a one-element tuple." |
It's just 42 in parentheses. You need (42,) — the comma makes the tuple. |
"d.get(k) returning None means the key is absent." |
The key may exist with value None. Check k in d when the distinction matters — JSON null makes this common (4.1). |
| "Iterating a dict gives you its items." | It yields keys. Use d.items() for (key, value) pairs (4.2). |
"in on a dict checks keys and values." |
in tests keys only; use in d.values() for values (4.2). |
"Dicts are unordered / OrderedDict is required for order." |
Insertion order is guaranteed since Python 3.7; plain dict suffices except for move_to_end (4.2, 4.8). |
| "Any object can be a dict key." | Keys must be hashable — immutable. Lists, dicts and sets raise TypeError; tuples work only if everything inside is hashable (4.4). |
"sorted() and sort() are interchangeable." |
sorted() returns a new list; sort() mutates in place and returns None — x = x.sort() sets x to None (2.3). |
"sorted(xs, reverse=True) is the same as reversing the sorted list." |
It isn't: the sort stays stable, so equal-keyed items keep input order; reversed(sorted(...)) flips them. reverse=True also reverses every key in a tuple key at once (2.3). |
| "Sets preserve insertion order." | They don't — order is arbitrary (hash-dependent). Use dict.fromkeys for order-preserving dedupe (5.1). |
"s.remove(x) and s.discard(x) are interchangeable." |
remove raises KeyError on a missing element; discard silently ignores it — same trap family as d[key] vs d.get (5.3). |
"list.remove(x) deletes by index." |
It deletes the first item equal to x; use pop(i)/del for positions (2.2). |
"a | b works on any iterable." |
Set/dict | requires both operands to be sets/dicts; the methods (a.union(...)) accept any iterable (5.2). |
| "A tuple of dicts is a safe immutable record." | The tuple is frozen but the dicts inside are still mutable — shallow immutability again (3.2). |
| "JSON round-trips preserve types." | Tuples become lists and non-string keys become strings — build JSON-safe shapes (str keys, lists, scalars) (4.9). |
Key takeaways#
- Names label objects; assignment binds, never copies.
isdetects sharing;==compares values. Mutables (list, dict, set) change in place and are dangerous to share; immutables (int, str, tuple, frozenset) can't be edited so sharing is safe. - Copy deliberately:
a[:]/list(a)/copy.copyfor shallow,copy.deepcopyfor nested independence. Silent mutation of caller data is a top production bug. - Lists: O(1) index/append, O(n) search;
sorted/sortwithkey=and guaranteed stability; multi-key sorts via tuple keys; never mutate while iterating;[[0]*n]*mshares rows — use a comprehension. - Tuples: immutable sequences for records, composite dict keys and multi-value returns;
(x,)needs the comma; immutability is shallow;namedtuplefor tiny named records,dataclassbeyond that. - Dicts are the engine:
[]/get/setdefaultfor reads; insertion order guaranteed (3.7+);|/|=/{**a, **b}merge with right-side-wins;pop(k, default)for safe removal; keys/values/items views are live;intests keys only. - Hashability gates keys: immutable → hashable; tuples hashable only if contents are;
True == 1as keys;frozensetfor immutable sets. - Nested data:
get_path(obj, path, default)is the safe-traversal helper for API-shaped dicts; lists of dicts are the record shape — filter, group (defaultdict), count (Counter), sort (key=), index ({id: record}), dedupe (set/dict.fromkeys). - Sets: O(1) membership, unordered, unique; algebra
| & - ^, subsets<=/>=and proper</>; methods accept any iterable, operators (and|=/&=/-=/^=) need sets;removeraises vsdiscardsilent;popremoves an arbitrary element;dict.fromkeysfor order-preserving dedupe and zeroed lookup tables. - Choose by cost: list for ordered mutable sequences, dict for key→value, set for membership/algebra, tuple for fixed bundles,
dequefor queues,heapq/bisectfor priority/sorted-insert,array/NumPy for bulk numbers. - JSON shapes: dicts with string keys + lists + scalars round-trip cleanly; tuples→lists, int keys→strings.
Where you'll use this in the AI path#
| Later you will... | The skill it leans on |
|---|---|
Build and send messages=[{...}, {...}] conversation lists |
4.6 Lists of dicts, then 03.2 |
Parse tool_calls[0].function.arguments (a JSON string) into a dict and validate it |
4.5 Nested dicts, then 03.5 |
Attach metadata={...} to every chunk for filtering |
4.8 collections helpers, then 05.8 |
| Dedupe ids before embedding, batch records for APIs | Part 5: Sets, then 06.2 |
Reconcile batch results by custom_id |
dict index-by-id, then 03.9 |
| Handle stream events that arrive as dicts | 4.5 get_path, then 03.3 |
| Read/write the ticket data as CSV/JSON | Part 7, then 01A.9 |
Turn each ticket dict into a typed Ticket |
Part 7, then 01A.6 and 01B.6 |
Terms introduced in this lesson#
| Term | One-line definition |
|---|---|
| Name binding | Assignment attaches a name to an object; it never copies the object |
| Object | The actual data a name points at; names are labels, not containers |
| Mutable / immutable | Can be changed in place / any change produces a new object |
| Alias | A second name for the same object (b = a) |
| Shallow copy | New outer container sharing nested objects (a[:], .copy()) |
| Deep copy | Recursive copy of the whole object graph (copy.deepcopy) |
| Hashable | Has a stable hash consistent with equality; required for dict keys and set members |
| List | Ordered, mutable sequence; O(1) indexing and append, O(n) search |
| Slice | start:stop:step sub-sequence that always produces a new sequence and never raises on out-of-range indexes |
| Stability (sort) | Equal-keyed items keep their original relative order |
| Tuple | Ordered, immutable sequence; used for records, keys and multi-value returns |
namedtuple |
Tuple with named fields; tiny fixed record, still a plain tuple |
| Dictionary (dict) | Key→value mapping; insertion-ordered since Python 3.7; the shape of JSON objects |
get / setdefault |
Safe read with default / read-or-create-default |
| Dict view | Live keys()/values()/items() reflection of a dict |
| Insertion order | Dict iteration order = order keys were first added (guaranteed 3.7+) |
defaultdict |
Dict that auto-creates missing keys via a factory (int, list, ...) |
Counter |
Dict subclass specialised for counting items |
OrderedDict |
Dict with order guarantee plus move_to_end; mostly superseded by dict |
ChainMap |
Stack of dicts: lookup falls through layers, writes hit the first |
| Set | Unordered collection of unique hashable items; O(1) membership |
| Set algebra | | union, & intersection, - difference, ^ symmetric difference |
frozenset |
Immutable, hashable set; usable as a dict key or set member |
deque |
Double-ended queue with O(1) append/pop at both ends |
| List of dicts | The record shape: a list whose items are same-schema dicts (JSON rows) |
get_path |
Helper walking a mixed dict-key/list-index path with a default fallback |
| Big-O | Cost growth rate of an operation as input size grows |
| Amortised O(1) | Occasionally costly operation averaging to constant time (list append) |
heapq / bisect |
Priority-queue / sorted-insert helpers over plain lists |
array.array |
Compact typed numeric storage, one C type per array |
All terms are also collected in the glossary.
Exercises#
Run the code from this lesson and experiment. Solutions for all items are in the single collapsible block at the end of this section.
- Slicing (2.1): given
levels = ["debug", "info", "warning", "error", "critical"], print the last two elements, the list reversed, the middle two, and every second element. - The grid trap (2.6): this code prints three identical rows. Fix it so only row 0, col 0 is
1:python grid = [[0] * 3] * 3 grid[0][0] = 1 - Stability and multi-key sort (2.3):
players = [("kim", 90), ("max", 85), ("sam", 90), ("jo", 70), ("ali", 85)]. Sort by score ascending and show that ties keep input order; then sort score descending, name ascending. - Copy before mutating (1.3, 2.5): write
add_tag(config, tag)that returns a new config dict withtagappended toconfig["tags"]without mutating the caller's dict. Prove independence. - Tuples (3.1): write
def extremes(numbers)returning(min, max); unpack the result. Then show why(42)is not a tuple but(42,)is. - Safe counting (4.1, 4.8): write two
tally(words)functions — one withdict.get, one withdefaultdict(int)— and show they agree. - Merge without mutation (4.3):
DEFAULTS = {"model": "gpt-6-luna", "timeout_s": 30, "max_output_tokens": 500}anduser_overrides = {"timeout_s": 60, "stream": True}. Build the effective config with|and proveDEFAULTSis unchanged. get_path(4.5): reuse the helper on{"data": {"items": [{"sku": "A-1", "price": {"amount": 1299, "currency": "USD"}}, {"sku": "B-2", "price": {"amount": 450, "currency": "USD"}}]}}. Extract the amount of item 1 and the currency of item 0; then a path that doesn't exist with a default.- Group and count (4.6, 7): using the lesson's
TICKETS, count open tickets per category withCounter. - Tuple keys (4.4, 4.6): count
TICKETSby(category, priority)using tuple keys; then show why a list key fails. - Set algebra (5.2):
expected = {"created", "updated", "deleted", "ping"},received = {"created", "updated", "created_retry", "pong"}. Compute missing, unexpected and correctly-handled event types. - Order-preserving dedupe (5.1): dedupe
["zoe@example.com", "amy@example.com", "bo@example.com", "amy@example.com", "zoe@example.com", "cy@example.com", "bo@example.com", "amy@example.com"]keeping first-seen order, and contrast withset. - Bounded deque (2.7): write
tail(lines, n=3)usingdeque(maxlen=n)that returns the lastnitems oflines; test on a 6-line log. - heapq + bisect (6.4):
latencies = [120, 340, 95, 410, 180, 260, 88]— find the 3 slowest withheapq.nlargest; theninsort300into[100, 250, 500]and find the first slot>= 300withbisect_left. - Index by customer (7): build
{customer: [ticket_ids]}fromTICKETSusingdefaultdict(list)and print each customer's ids sorted.
Solutions
1. Slicing
levels = ["debug", "info", "warning", "error", "critical"]
print("last two :", levels[-2:])
print("reversed :", levels[::-1])
print("middle two :", levels[1:3])
print("every other :", levels[::2])last two : ['error', 'critical']
reversed : ['critical', 'error', 'warning', 'info', 'debug']
middle two : ['info', 'warning']
every other : ['debug', 'warning', 'critical']2. The grid trap — [[0] * 3] * 3 repeats the reference to one inner list; a comprehension builds a fresh list per row:
buggy = [[0] * 3] * 3
buggy[0][0] = 1
fixed = [[0] * 3 for _ in range(3)]
fixed[0][0] = 1
for row in buggy: print(" ", row)
for row in fixed: print(" ", row) [1, 0, 0]
[1, 0, 0]
[1, 0, 0]
[1, 0, 0]
[0, 0, 0]
[0, 0, 0]3. Stability and multi-key sort
players = [("kim", 90), ("max", 85), ("sam", 90), ("jo", 70), ("ali", 85)]
for name, score in sorted(players, key=lambda p: p[1]):
print(f" {name}: {score}")
for name, score in sorted(players, key=lambda p: (-p[1], p[0])):
print(f" {name}: {score}") jo: 70
max: 85
ali: 85
kim: 90
sam: 90
kim: 90
sam: 90
ali: 85
max: 85
jo: 70max before ali and kim before sam in the first sort — ties kept input order (stability). The tuple key (-score, name) sorts score descending then name ascending in one pass.
4. Copy before mutating
import copy
def add_tag(config, tag):
new_config = copy.deepcopy(config)
new_config["tags"].append(tag)
return new_config
config = {"name": "prod-api", "tags": ["v1", "stable"]}
updated = add_tag(config, "canary")
print("original:", config)
print("updated :", updated)
print("independent:", config["tags"] is not updated["tags"])original: {'name': 'prod-api', 'tags': ['v1', 'stable']}
updated : {'name': 'prod-api', 'tags': ['v1', 'stable', 'canary']}
independent: Truedeepcopy is needed because tags is a nested list — a shallow .copy() would share it.
5. Tuples
def extremes(numbers):
return min(numbers), max(numbers)
lo, hi = extremes([4, 1, 9, 2])
print("lo:", lo, "hi:", hi)
print("42 :", type(42).__name__)
print("(42,) :", type((42,)).__name__, (42,))lo: 1 hi: 9
42 : int
(42,) : tuple (42,)return min, max packs a tuple; the caller's lo, hi = unpacks it. (42) is an int; the comma makes (42,) a tuple.
6. Safe counting
def tally_get(words):
counts = {}
for w in words:
counts[w] = counts.get(w, 0) + 1
return counts
def tally_defaultdict(words):
from collections import defaultdict
counts = defaultdict(int)
for w in words:
counts[w] += 1
return counts
words = "cat dog cat bird cat dog".split()
print("dict.get :", tally_get(words))
print("defaultdict :", dict(tally_defaultdict(words)))dict.get : {'cat': 3, 'dog': 2, 'bird': 1}
defaultdict : {'cat': 3, 'dog': 2, 'bird': 1}7. Merge without mutation
DEFAULTS = {"model": "gpt-6-luna", "timeout_s": 30, "max_output_tokens": 500}
user_overrides = {"timeout_s": 60, "stream": True}
cfg = DEFAULTS | user_overrides
print("config :", cfg)
print("defaults still:", DEFAULTS)
print("defaults is cfg:", DEFAULTS is cfg)config : {'model': 'gpt-6-luna', 'timeout_s': 60, 'max_output_tokens': 500, 'stream': True}
defaults still: {'model': 'gpt-6-luna', 'timeout_s': 30, 'max_output_tokens': 500}
defaults is cfg: False| returns a new dict — DEFAULTS is untouched and cfg is a different object.
8. get_path
def get_path(obj, path, default=None):
cur = obj
for key in path:
if isinstance(cur, dict) and key in cur:
cur = cur[key]
elif isinstance(cur, list) and isinstance(key, int) and 0 <= key < len(cur):
cur = cur[key]
else:
return default
return cur
order = {"data": {"items": [
{"sku": "A-1", "price": {"amount": 1299, "currency": "USD"}},
{"sku": "B-2", "price": {"amount": 450, "currency": "USD"}},
]}}
print(get_path(order, ["data", "items", 1, "price", "amount"]))
print(get_path(order, ["data", "items", 0, "price", "currency"]))
print(get_path(order, ["data", "items", 5, "sku"], "missing"))
print(get_path(order, ["data", "items", 0, "price", "tax"], None))450
USD
missing
None9. Group and count
from collections import Counter
TICKETS = [
{"id": "T-1042", "category": "account", "status": "open"},
{"id": "T-1043", "category": "billing", "status": "open"},
{"id": "T-1044", "category": "bug", "status": "in-progress"},
{"id": "T-1045", "category": "feature", "status": "open"},
{"id": "T-1046", "category": "account", "status": "resolved"},
{"id": "T-1047", "category": "billing", "status": "open"},
{"id": "T-1044", "category": "bug", "status": "open"},
{"id": "T-1048", "category": "bug", "status": "closed"},
]
open_by_category = Counter(t["category"] for t in TICKETS if t["status"] == "open")
print("open tickets by category:", open_by_category.most_common())open tickets by category: [('billing', 2), ('account', 1), ('feature', 1), ('bug', 1)]10. Tuple keys
from collections import Counter
TICKETS = [
{"id": "T-1042", "category": "account", "priority": "high"},
{"id": "T-1043", "category": "billing", "priority": "medium"},
{"id": "T-1044", "category": "bug", "priority": "urgent"},
{"id": "T-1047", "category": "billing", "priority": "urgent"},
{"id": "T-1046", "category": "account", "priority": "high"},
]
counts = Counter((t["category"], t["priority"]) for t in TICKETS)
for key, n in sorted(counts.items()):
print(f" {key}: {n}")
try:
Counter(([t["category"], t["priority"]] for t in TICKETS))
except TypeError as e:
print("list key ->", e) ('account', 'high'): 2
('billing', 'medium'): 1
('billing', 'urgent'): 1
('bug', 'urgent'): 1
list key -> unhashable type: 'list'Tuples are hashable composite keys; lists are not.
11. Set algebra
expected = {"created", "updated", "deleted", "ping"}
received = {"created", "updated", "created_retry", "pong"}
print("missing:", sorted(expected - received))
print("unexpected:", sorted(received - expected))
print("handled:", sorted(expected & received))
print("symmetric difference:", sorted(expected ^ received))
print("all covered?", expected <= received)missing: ['deleted', 'ping']
unexpected: ['created_retry', 'pong']
handled: ['created', 'updated']
symmetric difference: ['created_retry', 'deleted', 'ping', 'pong']
all covered? False12. Order-preserving dedupe
emails = ["zoe@example.com", "amy@example.com", "bo@example.com",
"amy@example.com", "zoe@example.com", "cy@example.com",
"bo@example.com", "amy@example.com"]
print("first-seen order :", list(dict.fromkeys(emails)))
print("set, sorted for display:", sorted(set(emails)))first-seen order : ['zoe@example.com', 'amy@example.com', 'bo@example.com', 'cy@example.com']
set, sorted for display: ['amy@example.com', 'bo@example.com', 'cy@example.com', 'zoe@example.com']dict.fromkeys keeps first-seen order; a bare set would give hash-dependent order that differs between runs — always sorted(set(...)) when you need to show it.
13. Bounded deque
from collections import deque
def tail(lines, n=3):
buf = deque(maxlen=n)
for line in lines:
buf.append(line)
return list(buf)
log = ["start", "req 1 ok", "req 2 ok", "req 3 fail", "req 4 ok", "shutdown"]
print("last 3 log lines:", tail(log))
print("last 2 :", tail(log, 2))last 3 log lines: ['req 3 fail', 'req 4 ok', 'shutdown']
last 2 : ['req 4 ok', 'shutdown']maxlen makes the deque a ring buffer: append on a full deque drops the oldest item automatically.
14. heapq + bisect
import bisect
import heapq
latencies = [120, 340, 95, 410, 180, 260, 88]
print("3 slowest (ms):", heapq.nlargest(3, latencies))
thresholds = [100, 250, 500]
bisect.insort(thresholds, 300)
print("thresholds after insort(300):", thresholds)
print("first slot >= 300 (bisect_left):", bisect.bisect_left(thresholds, 300))3 slowest (ms): [410, 340, 260]
thresholds after insort(300): [100, 250, 300, 500]
first slot >= 300 (bisect_left): 215. Index by customer
from collections import defaultdict
TICKETS = [
{"id": "T-1042", "customer": "ana@example.com"},
{"id": "T-1043", "customer": "bo@example.com"},
{"id": "T-1044", "customer": "cy@example.com"},
{"id": "T-1046", "customer": "ana@example.com"},
{"id": "T-1047", "customer": "bo@example.com"},
{"id": "T-1048", "customer": "di@example.com"},
]
by_customer = defaultdict(list)
for t in TICKETS:
by_customer[t["customer"]].append(t["id"])
for customer in sorted(by_customer):
print(f" {customer}: {by_customer[customer]}") ana@example.com: ['T-1042', 'T-1046']
bo@example.com: ['T-1043', 'T-1047']
cy@example.com: ['T-1044']
di@example.com: ['T-1048']Check yourself#
- What does
b = ado whenais a list — copy or share? How do you make an independent copy?It shares —bbecomes a second name for the same list object. Independent copies:a[:],list(a),copy.copy(a)for shallow;copy.deepcopy(a)for nested independence. - Why can't a list be a dict key, but a tuple can?A list is mutable → unhashable (its contents can change, so no stable hash). A tuple is immutable → hashable, provided everything inside it is also hashable.
- What's the difference between
lst.sort()andsorted(lst)?lst.sort()sorts in place and returnsNone;sorted(lst)returns a new sorted list and leaveslstuntouched.x = x.sort()is a bug — it setsxtoNone. - Why does
sortedkeep("ana", 3)before("cy", 3)when both have key3?Python's sort is stable: items with equal keys keep their original relative order. That's also why multi-key sorts work via tuple keys or sort-twice. - What does
(42)evaluate to, and how do you write a one-element tuple?(42)is just42(an int) in parentheses. The one-element tuple is(42,)— the trailing comma is required. - A tuple contains a list. Is the tuple hashable? Why or why not?No. Hashability is recursive: the tuple is only as hashable as its contents, and a list inside is unhashable, making the whole tuple unhashable.
d = {"a": None}ande = {}. What doesd.get("a")return vse.get("a"), and why is that a problem?Both returnNone.d.get("a")returnsNonebecause the key exists with valueNone;e.get("a")returnsNonebecause the key is absent. You can't distinguish "present but null" from "absent" — check"a" in dwhen it matters.- Iterating
for x in my_dictyields what — keys, values, or items?Keys.for k, v in d.items()yields(key, value)pairs;d.values()yields values. - Since which Python version is dict insertion order guaranteed?Python 3.7 (guaranteed as language spec; CPython 3.6 had it as an implementation detail).
- What's the difference between
d.update(other)andd | other?updatemutatesdin place;|returns a new dict (|=mutates). Both let the right side win on key clashes. - When would you use
setvsdict.fromkeysfor deduplication?setwhen order doesn't matter and you want the fastest dedupe plus set algebra;dict.fromkeyswhen you need first-seen order preserved. - Why is
x in my_listslow at scale, and what structure fixes it?List membership scans every item — O(n). Aset(or dict keyed by the value) hashes straight to the item — O(1). Build an index once, look up many times. a | [1, 2]raisesTypeErrorbuta.union([1, 2])works. Why?|requires both operands to be sets/dicts;union()is a method that accepts any iterable (lists, generators, dict keys).- In the ticket toolkit, why does
by_idmapT-1044to the second record, and what should you do about it?The dict comprehension{t["id"]: t for t in TICKETS}lets later duplicates overwrite earlier ones — last-wins. Decide the policy explicitly: detect duplicates first (asfind_duplicate_idsdoes), or usesetdefaultfor first-wins, or reject the data.
Further resources#
- Python Tutorial: Data Structures (official docs): lists, tuples, dicts, sets, comprehensions — the canonical reference this lesson expands on.
- Built-in Types — Python docs: the authoritative spec for
list,tuple,dict,set,frozenset, slicing and the method tables. collections— Python docs:deque,Counter,defaultdict,namedtuple,OrderedDict,ChainMap.copy— Python docs: shallow vs deep copy semantics.heapq,bisect,array: the auxiliary containers.- What's New in Python 3.7: the change that made dict insertion order part of the language.
json— Python docs: what survives a JSON round trip (tuples→lists, int keys→strings).- Luciano Ramalho, Fluent Python (O'Reilly): the deepest practical treatment of the data model — names/objects, mutability and the collections ABCs. Read chapters 1–3 after this lesson.
← 01A.3 — Control Flow and Functions | Module 01A overview | 01A.5 — Comprehensions, Iterators and Generators →