Python Masterclass / Module 6 of 10 Phase 2: Language Core & CPython Internals

Python Data Structures & Commonly Used Methods — Built-Ins, Collections, Custom Trees/Graphs & Big-O

42 min study + 3 Live Wasm Labs
⚡ Answer-First Executive Summary (TL;DR) Module 6 Key Takeaways
  • ✓ Built-In Core: list (dynamic PyObject* array; use .append/.pop/.sort/slicing), tuple & NamedTuple (immutable hashable records), dict (compact insertion-ordered hash map; use .get/.setdefault/.pop/.items and | merge), set & frozenset (O(1) membership & set algebra | & - ^), and str/bytearray (use "".join, .split, .partition, .removeprefix).
  • ✓ Standard Library Powerhouses: collections.deque (strictly O(1) .appendleft/.popleft/.rotate & maxlen ring buffers), Counter (.most_common, .total, multiset math), defaultdict(list/int/set), OrderedDict (.move_to_end & .popitem(last=False) for O(1) LRU caches), ChainMap, heapq (heappush, heappop, heapify, heappushpop, nlargest, merge), bisect (bisect_left, insort), array.array, and graphlib.TopologicalSorter.
  • ✓ Critical Method Gotchas: list.sort() sorts in-place and returns None (use sorted(it) for a new list); str.strip("abc") strips a character set—always use str.removeprefix() / removesuffix() for substrings; set.discard(x) never raises KeyError unlike set.remove(x); defaultdict.get(k) does NOT trigger default_factory unlike d[k].
  • ✓ Custom Interview & Systems Structures: Build Linked Lists (ListNode), Binary Trees (TreeNode), Tries (TrieNode with __slots__), Graphs (defaultdict(list)), and Disjoint Set / Union-Find (path compression + rank) cleanly in 15–25 lines of idiomatic Python.

01. Master Big-O Time & Space Complexity Matrix (All 18 Python Data Structures)

Every staff coding or systems architecture review requires knowing the exact average-case, worst-case, and C backing representation of Python’s built-in, standard library, and custom data structures:

Table 6.1 — Complete Python Data Structure Catalog: Backing Layout & Operation Big-O
Data Structure Module / Type Internal Backing Structure Index / Key Get Search (x in s) Insert / Push Right Insert / Pop Left (0) Delete Arbitrary
list built-in Contiguous PyObject** array (~1.125x growth) O(1) O(n) O(1) amort O(n) memmove O(n)
tuple / NamedTuple built-in / typing Immutable inline PyObject* ob_item[] struct O(1) O(n) Immutable Immutable Immutable
str / bytes built-in Immutable PEP 393 1/2/4B buffer / raw octet array O(1) O(n) O(n) new copy O(n) new copy Immutable
bytearray built-in Mutable dynamic raw char* buffer with head offset O(1) O(n) O(1) amort O(1) amort O(n)
range built-in 3 integers (start, stop, step) — 48B constant RAM! O(1) math O(1) math! Immutable Immutable Immutable
dict built-in Compact Hash Table (dk_indices + dense dk_entries) O(1) avg O(1) avg (key) O(1) amort N/A O(1) avg
set / frozenset built-in Open-Addressed Hash Table with linear cache probing N/A O(1) avg O(1) (add) N/A O(1) (discard)
deque collections Doubly-linked list of 64-pointer C blocks O(1) ends / O(n) mid O(n) O(1) strict O(1) strict O(n)
defaultdict / Counter collections dict subclass overriding __missing__(key) O(1) avg O(1) avg O(1) avg N/A O(1) avg
OrderedDict collections dict + doubly-linked list for O(1) move_to_end O(1) avg O(1) avg O(1) avg O(1) (last=False) O(1) avg
heapq heapq (on list) Implicit binary min-heap (children: 2i+1, 2i+2) O(1) min (h[0]) O(n) O(log n) push O(log n) pop-min O(n)
bisect (on sorted list) bisect C binary search over contiguous sorted list O(1) O(log n) bisect O(n) (insort) O(n) O(n)
array.array array Contiguous unboxed C primitives ('q'=8B int64, 'd'=8B float) O(1) O(n) O(1) amort O(n) O(n)
Trie (Prefix Tree) custom / dict Tree of children: dict[str, TrieNode] of word length L O(L) prefix O(L) exact O(L) insert N/A O(L)
Union-Find (DSU) custom (2 lists) parent[] + size[] arrays with path compression O(α(n)) ≈ O(1) O(α(n)) connected O(α(n)) union N/A N/A

02. Core Built-In Data Structures & Complete Method Reference (list, dict, set, str, tuple)

Below is the complete method & idiom directory for Python’s built-in collections, including exact return values, time complexities, and interview/production patterns:

1. Built-In Sequence & LIFO Stack

list — Dynamic Contiguous Pointer Array (PyListObject)

11 Methods + Slicing + Comprehensions
Essential Methods & Signatures
  • • lst.append(x) → None: Push x to right end in O(1) amortized (use as LIFO stack push).
  • • lst.pop(i=-1) → item: Remove & return last item in O(1); lst.pop(0) is O(n) (use deque.popleft() instead!).
  • • lst.extend(iterable) → None: Batch-append all items from iterable in O(k) (faster than lst = lst + other which allocates a new list).
  • • lst.insert(i, x) → None: Insert x before index i, shifting subsequent pointers right in O(n).
  • • lst.remove(x) → None: Remove first occurrence of x in O(n) (raises ValueError if absent).
  • • lst.index(x, start=0, stop=len) & lst.count(x): Linear scan in O(n).
  • • lst.sort(*, key=None, reverse=False) → None: In-place adaptive Timsort (O(n log n) worst, O(n) on nearly-sorted runs, stable). Use sorted(it, key=...) when you need a new list.
  • • lst.reverse() → None (in-place O(n)) vs. reversed(lst) (O(1) iterator) vs. lst[::-1] (O(n) reversed shallow copy).
  • • lst.copy() (or lst[:]) & lst.clear(): Shallow copy (O(n)) vs. emptying all slots (O(n) decref).
# 1. Creation, Comprehension & Safe 2D Matrix Init
nums = [10, 20, 30, 40]
squares = [x * x for x in nums if x > 15]   # [400, 900, 1600]
grid = [[0] * 4 for _ in range(3)]          # 3 independent rows of 4 zeros

# 2. Stack (LIFO) & In-Place Slice Mutation
nums.append(50)                             # [10, 20, 30, 40, 50]
top = nums.pop()                            # 50 (O(1))
nums[1:3] = [25, 35, 38]                    # Replace slice in-place!

# 3. Custom Multi-Key Timsort (Sort by score DESC, then name ASC)
users = [("alice", 95), ("bob", 88), ("carol", 95)]
users.sort(key=lambda u: (-u[1], u[0]))     # [('alice', 95), ('carol', 95), ('bob', 88)]

# 4. Slicing & Enumerate / Zip Iteration
evens_reversed = nums[::-2]                 # Stride -2 from end to start
for idx, (name, score) in enumerate(users, start=1):
    pass
2. Built-In Hash Map (Insertion-Ordered)

dict — Compact Open-Addressing Hash Table (PyDictObject)

11 Methods + Set-Like Views + PEP 584 Union
Essential Methods & Signatures
  • • d.get(key, default=None) → val: Safe O(1) lookup that returns default instead of raising KeyError.
  • • d.setdefault(key, default=None) → val: Returns d[key] if present; otherwise inserts d[key] = default and returns it (O(1)).
  • • d.pop(key[, default]) → val: Removes key and returns its value in O(1) (never raises KeyError when default is supplied).
  • • d.popitem() → (k, v): Removes & returns the most recently inserted (key, value) pair in LIFO order (O(1)).
  • • d.update(other, **kw) & d1 | d2 / d1 |= d2: Merge dictionaries (right-hand keys win on collision).
  • • d.keys(), d.values(), d.items(): Dynamic O(1) view objects; keys() and items() support set operations (d1.keys() & d2.keys())!
  • • dict.fromkeys(iterable, value=None): Creates a dict with shared initial value (avoid passing a mutable [] as value!).
# 1. Safe Lookups, Grouping with setdefault & Pop with Fallback
index: dict[str, int] = {"alpha": 1, "beta": 2}
val = index.get("gamma", 0)                 # 0 (no KeyError)
removed = index.pop("missing_key", None)    # None (safe delete)

groups: dict[str, list[str]] = {}
for dept, emp in [("ai", "Ada"), ("infra", "Linus"), ("ai", "Grace")]:
    groups.setdefault(dept, []).append(emp) # {'ai': ['Ada', 'Grace'], 'infra': ['Linus']}

# 2. Dict Comprehension, PEP 584 Merge (|) & Key-View Set Algebra
inverted = {v: k for k, v in index.items()}
merged = {"timeout": 10, "tls": True} | {"timeout": 30, "Pool": 8}

common_keys = index.keys() & {"beta", "delta"}  # {'beta'} in O(min(len))
# 3. Sort Dictionary by Value Descending
top_pairs = sorted(index.items(), key=lambda kv: kv[1], reverse=True)
3. Built-In Unique Collection & Algebra

set & frozenset — Hash Set (PySetObject)

17 Methods + Bitwise Set Algebra
Essential Methods & Set Algebra
  • • s.add(x) & s.update(*iterables) (|=): Insert single element (O(1)) or multiple iterables (O(k)).
  • • s.discard(x) vs s.remove(x): Both delete x in O(1), but discard(x) never raises KeyError if x is missing!
  • • Union: a | b or a.union(it) — elements in either set (O(|a| + |b|)).
  • • Intersection: a & b or a.intersection(it) — elements in both sets (O(min(|a|, |b|))).
  • • Difference: a - b or a.difference(it) — elements in a but not b.
  • • Symmetric Difference (XOR): a ^ b or a.symmetric_difference(it) — elements in exactly one set.
  • • Comparisons: a <= b (issubset), a < b (proper subset), a >= b (issuperset), and a.isdisjoint(b) (fast early-exit overlap check).
  • • frozenset(iterable): Immutable, hashable set usable as a dictionary key or an element inside another set!
# 1. Note: Empty set MUST use set(), because {} creates an empty dict!
visited: set[tuple[int, int]] = set()
visited.add((0, 0))
visited.discard((99, 99))                   # Safe no-op (no KeyError!)

# 2. Set Algebra for Permission & Graph Frontier Filtering
granted = {"read", "write", "execute"}
required = {"read", "write"}
assert required <= granted                  # Subset check (issubset)
missing_perms = required - granted          # set()
exclusive = granted ^ {"write", "admin"}    # {'read', 'execute', 'admin'}

# 3. Order-Preserving Deduplication of a List in O(n)
raw_items = ["mcp", "a2a", "mcp", "rag", "a2a"]
unique_ordered = list(dict.fromkeys(raw_items))  # ['mcp', 'a2a', 'rag']

# 4. frozenset as a Hashable Dict Key (e.g. Anagram Signature / DP State)
state_cache = {frozenset(["node_a", "node_b"]): 42}
4. Text & Binary Sequences

str, bytes & bytearray — 22 High-Frequency String & Buffer Methods

Search • Split/Join • Prefix/Suffix • ASCII Math
Essential Methods & Signatures
  • • Joining & Splitting: sep.join(iterable) (O(n) single allocation—never do s += chunk in a loop!), s.split(sep=None, maxsplit=-1) (default splits on any whitespace run), s.rsplit(sep, maxsplit), s.splitlines(), s.partition(sep) → (head, sep, tail).
  • • Trimming & Exact Affixes: s.strip(chars=None), s.lstrip(), s.rstrip() (character sets) vs. s.removeprefix(p) & s.removesuffix(sfx) (exact substring removal, Python 3.9+).
  • • Searching: s.find(sub, start, end) (returns -1 if absent) vs. s.index(sub) (raises ValueError), s.rfind(sub), s.count(sub), s.startswith(prefix_or_tuple), s.endswith(suffix_or_tuple).
  • • Character Tests & Transforms: s.isalnum(), s.isalpha(), s.isdigit(), s.islower(), s.isupper(), s.lower(), s.upper(), s.replace(old, new, count=-1), ord('a') == 97 ↔ chr(97) == 'a'.
# 1. Prefix/Suffix Removal & 3-Tuple Partitioning
route = "https://aiagent.org/api/v1/mcp.json"
clean_path = route.removeprefix("https://aiagent.org").removesuffix(".json")
host, _, endpoint = "db.internal:5432".partition(":")  # ('db.internal', ':', '5432')

# 2. Tuple Argument in startswith/endswith & Character Filtering
if route.endswith((".json", ".yaml", ".toml")):
    alnum_only = "".join(ch.lower() for ch in route if ch.isalnum())

# 3. 26-Bucket ASCII Frequency Array via ord(ch) - ord('a')
freq = [0] * 26
for ch in "anagram":
    freq[ord(ch) - ord("a")] += 1
signature = tuple(freq)  # Hashable O(1) anagram key!

# 4. Mutable bytearray for In-Place Binary Protocol Framing
buf = bytearray(b"PING")
buf[1] = ord("O")        # Mutates in-place to bytearray(b'PONG')
5. Immutable Records & Lazy Sequences

tuple, typing.NamedTuple & range

Hashable Composite Keys • Zero-Dict Records • O(1) Range Math
  • • tuple methods: t.count(x) and t.index(x). Because tuples store element pointers inline inside PyTupleObject (1 allocation instead of 2 for list) and cache freed blocks of size 1–20, they are faster to allocate and valid as dict/set keys.
  • • typing.NamedTuple: Subclasses tuple with zero per-instance __dict__ overhead while adding typed field names, rec._asdict(), rec._replace(**kw), and rec._fields.
  • • range(start, stop, step=1): Computes len(r), r[i], r[a:b], and x in r via closed-form arithmetic in O(1) time and 48 bytes of RAM even for range(0, 10**18, 7)!
from typing import NamedTuple

class GridCoord(NamedTuple):
    row: int
    col: int
    layer: str = "L0"

pt = GridCoord(3, 5)
# Supports BOTH attribute access (pt.row) and tuple unpacking (r, c, l = pt)!
moved = pt._replace(col=6)                  # Returns new GridCoord(3, 6, 'L0')
as_map = moved._asdict()                    # {'row': 3, 'col': 6, 'layer': 'L0'}

# O(1) closed-form arithmetic containment on a 1-trillion element range:
huge_steps = range(0, 10**12, 25)
assert (250_000_000_000 in huge_steps) is True

03. Standard Library Collections & Specialized Containers (collections, heapq, bisect, array, graphlib)

6. collections.deque (Double-Ended Queue & Ring Buffer)

O(1) Both Ends

Methods: append(x), appendleft(x), pop(), popleft(), extend(it), extendleft(it), rotate(k=1) (circular shift right +k or left -k), and deque(it, maxlen=N) bounded sliding window.

from collections import deque

# 1. BFS Queue & Circular Array Rotation
q = deque([10, 20, 30, 40])
q.appendleft(5)             # deque([5, 10, 20, 30, 40])
first = q.popleft()         # 5 in strict O(1)
q.rotate(1)                 # deque([40, 10, 20, 30])

# 2. Automatic Sliding Window Ring Buffer (tail N logs)
recent = deque(maxlen=3)
for i in range(5):
    recent.append(f"msg_{i}")  # Keeps only ['msg_2', 'msg_3', 'msg_4']

7. collections.Counter (Multiset & Frequency Bag)

Top-K & Bag Math

Methods: most_common(k=None) (O(n log k) via heap), total() (sum of all counts), elements(), update(it) (adds counts!), subtract(it), plus multiset operators +, - (drops ≤ 0), & (min), | (max).

from collections import Counter

c1 = Counter("abracadabra")
print(c1.most_common(2))    # [('a', 5), ('b', 2)]
print(c1["missing_char"])   # Returns 0 (never raises KeyError!)
print(c1.total())           # 11 (Python 3.10+)

# Multiset Substring / Anagram Window Containment Check!
need = Counter("aab")
window = Counter("cabba")
can_cover = (need - window) == Counter()  # True (or need <= window in 3.10+)

8. defaultdict, OrderedDict & ChainMap

Graphs • LRU • Scopes

defaultdict(list|set|int) auto-initializes missing keys on d[k]. OrderedDict adds O(1) move_to_end(k, last=True) and popitem(last=False). ChainMap(*dicts) layers multiple mappings without copying.

from collections import ChainMap, OrderedDict, defaultdict

# 1. Graph Adjacency List in 2 lines with defaultdict(list)
adj: defaultdict[int, list[int]] = defaultdict(list)
for u, v in [(0, 1), (0, 2), (1, 3)]:
    adj[u].append(v)

# 2. Layered Config Resolution without copying dicts (ChainMap)
cli_flags = {"model": "gemini-2.5-pro"}
env_Defaults = {"model": "gemini-2.5-flash", "timeout": 30}
cfg = ChainMap(cli_flags, env_Defaults)
assert cfg["model"] == "gemini-2.5-pro" and cfg["timeout"] == 30

9. heapq (Priority Queue) & bisect (Binary Search)

O(log n) Order

heapq: heapify(lst) (O(n)), heappush(h, x), heappop(h), heappushpop(h, x) (1 sift instead of 2!), heapreplace(h, x), nlargest(k, it), merge(*sorted_its).
bisect: bisect_left(a, x) (≥ x), bisect_right(a, x) (> x), insort(a, x).

import bisect
import heapq

# 1. Streaming Top-K Elements in O(n log k) using heappushpop
min_heap = [10, 20, 30]
heapq.heapify(min_heap)
for val in [5, 45, 25, 90]:
    if val > min_heap[0]:
        heapq.heappushpop(min_heap, val)    # Keeps top 3 largest: [25, 45, 90]

# 2. Lazy K-Way Sorted Stream Merge + Bisect Range Count
merged_stream = list(heapq.merge([1, 4, 9], [2, 5, 8]))  # [1, 2, 4, 5, 8, 9]
lo = bisect.bisect_left(merged_stream, 2)   # First index >= 2 (idx 1)
hi = bisect.bisect_right(merged_stream, 8)  # First index > 8  (idx 5)

04. Custom Interview & Systems Data Structures in Python (Linked List, Tree, Trie, Graph, Union-Find & TopologicalSorter)

When Python’s standard library does not provide a pointer-linked node structure out of the box (such as Singly/Doubly Linked Lists, Binary Trees, Tries, or Disjoint Set Union), use these minimal, slotted production templates:

10. Singly/Doubly Linked List & Binary Tree Node (__slots__)
class ListNode:
    __slots__ = ("val", "next")
    def __init__(self, val: int = 0, next: "ListNode | None" = None):
        self.val = val
        self.next = next

class TreeNode:
    __slots__ = ("val", "left", "right")
    def __init__(self, val: int = 0, left: "TreeNode | None" = None, right: "TreeNode | None" = None):
        self.val = val
        self.left = left
        self.right = right
11. Prefix Tree (Trie) with insert, search & starts_with
class TrieNode:
    __slots__ = ("children", "is_end")
    def __init__(self) -> None:
        self.children: dict[str, TrieNode] = {}
        self.is_end: bool = False

class Trie:
    def __init__(self) -> None:
        self.root = TrieNode()

    def insert(self, word: str) -> None:
        node = self.root
        for ch in word:
            node = node.children.setdefault(ch, TrieNode())
        node.is_end = True

    def search(self, word: str, *, prefix_only: bool = False) -> bool:
        node = self.root
        for ch in word:
            if ch not in node.children:
                return False
            node = node.children[ch]
        return True if prefix_only else node.is_end
12. Disjoint Set Union (Union-Find) — O(α(n)) Connectivity
class UnionFind:
    def __init__(self, n: int) -> None:
        self.parent = list(range(n))
        self.size = [1] * n
        self.components = n

    def find(self, x: int) -> int:
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]  # Path halving
            x = self.parent[x]
        return x

    def union(self, a: int, b: int) -> bool:
        ra, rb = self.find(a), self.find(b)
        if ra == rb:
            return False
        if self.size[ra] < self.size[rb]:
            ra, rb = rb, ra
        self.parent[rb] = ra
        self.size[ra] += self.size[rb]
        self.components -= 1
        return True
13. Standard Library DAG Topological Sort (graphlib)
from graphlib import CycleError, TopologicalSorter

# Built into Python 3.9+ stdlib! Maps node -> set of prerequisites
ts = TopologicalSorter({
    "deploy_agent": {"run_evals", "build_image"},
    "run_evals": {"compile_prompts"},
    "build_image": {"compile_prompts"},
})
# Returns deterministic topological execution order or raises CycleError:
execution_plan = list(ts.static_order())
# ['compile_prompts', 'run_evals', 'build_image', 'deploy_agent']

05. C-Level Compact dict Memory Layout & Scenario Selection Matrix

d = {"host": "db.internal", "port": 5432}

1. Sparse Hash Index Table (dk_indices: 8 slots × 1 byte = 8 bytes total!)
   ┌────┬────┬────┬────┬────┬────┬────┬────┐
   │ -1 │  0 │ -1 │ -1 │ -1 │  1 │ -1 │ -1 │   (hash("host") & 7 == 1 ──▶ index 0)
   └────┴──┬─┴────┴────┴────┴──┬─┴────┴────┘   (hash("port") & 7 == 5 ──▶ index 1)
           │                   └────────────────────┐
           ▼                                        ▼
2. Dense Insertion-Ordered Entries Array (dk_entries: 24 bytes per active entry)
   ┌───────┬────────────────────┬──────────────┬─────────────────┐
   │ Index │ me_hash (8B)       │ me_key* (8B) │ me_value* (8B)  │
   ├───────┼────────────────────┼──────────────┼─────────────────┤
   │   0   │ 0x38a9f102c4d81001 │ ──▶ "host"   │ ──▶ "db.intern" │
   │   1   │ 0x71b2049e8a110205 │ ──▶ "port"   │ ──▶ 5432        │
   └───────┴────────────────────┴──────────────┴─────────────────┘
• Collision Probing Formula: i = (5 * i + 1 + perturb) & mask; perturb >>= 5

💻 Hands-On WebAssembly Python Labs (Module 6)

Click Run & Edit Live (Wasm) on any lab below to execute and modify the code in our browser Pyodide runtime.

▶ Interactive Wasm Lab

Lab 6.1: Complete Built-In & Collections Methods Workbench (list, dict, set, str, deque, Counter, bisect)

Execute all high-frequency methods across list, dict, set, str, deque, Counter, defaultdict, heapq, and bisect in one interactive sandbox.

import bisect
from collections import Counter, defaultdict, deque
import heapq

# 1. list methods: append, extend, sort(key=...), slice assignment
tasks = ["lint", "build"]
tasks.append("test")
tasks.extend(["stage", "prod"])
tasks[1:3] = ["compile", "unit_test"]
print("[1] List Slice Mutation & Sort:", tasks)

# 2. dict methods: get, setdefault, pop, key-view intersection (&), PEP 584 merge (|)
cfg = {"retries": 3, "timeout": 10} | {"timeout": 25, "region": "us-east"}
cfg.setdefault("pool_size", 16)
removed_val = cfg.pop("legacy_flag", "not_present")
print("[2] Dict Merged & Setdefault:", cfg, "| pop fallback:", removed_val)
print("    Dict Key-View Intersection:", cfg.keys() & {"timeout", "region", "missing"})

# 3. set methods: add, discard (safe!), union (|), intersection (&), difference (-), XOR (^)
active = {"node_1", "node_2", "node_3"}
active.discard("node_99")  # Safe no-op
healthy = {"node_2", "node_3", "node_4"}
print("[3] Set Algebra -> Intersection:", active & healthy, "| Symmetric Diff (^):", active ^ healthy)

# 4. str methods: removeprefix, removesuffix, partition, join, startswith(tuple)
uri = "mcp://server.internal:8080/tools.json"
clean = uri.removeprefix("mcp://").removesuffix(".json")
host_port, _, path = clean.partition("/")
print(f"[4] String Partition -> host_port={host_port!r}, path={path!r}")

# 5. Counter multiset math, deque ring buffer & bisect binary search
c = Counter("mississippi")
print("[5] Counter top-2:", c.most_common(2), "| total:", c.total())
scores = [10, 25, 40, 55, 70]
bisect.insort(scores, 42)
print("    After bisect.insort(42):", scores, "| index of 42:", bisect.bisect_left(scores, 42))
▶ Interactive Wasm Lab

Lab 6.2: Observing CPython List Over-Allocation Steps & deque.popleft() vs list.pop(0) Benchmark

Run this script to watch exact byte jumps as a Python list reallocates its underlying C buffer and benchmark O(1) deque.popleft() vs O(n) list.pop(0).

from collections import deque
import sys
import time

# 1. Watch exact memory allocation jumps as a list grows from 0 to 32 elements
print("[1] PyListObject Geometric Over-Allocation Jumps:")
lst = []
prev_size = sys.getsizeof(lst)
print(f"    len=0  -> {prev_size} bytes (Empty PyListObject header = 56B)")
for i in range(1, 35):
    lst.append(i)
    curr_size = sys.getsizeof(lst)
    if curr_size != prev_size:
        capacity = (curr_size - 56) // 8
        print(f"    len={i:<2} -> resized to {curr_size:>3} bytes (Allocated pointer capacity = {capacity} slots)")
        prev_size = curr_size

# 2. Benchmark list.pop(0) O(n) vs collections.deque.popleft() O(1)
N = 40_000
q_list = list(range(N))
t0 = time.perf_counter()
while q_list:
    q_list.pop(0)  # Shifts remaining pointers on every single pop!
dt_list = (time.perf_counter() - t0) * 1000

q_deque = deque(range(N))
t0 = time.perf_counter()
while q_deque:
    q_deque.popleft()  # O(1) pointer increment inside 64-element C block
dt_deque = (time.perf_counter() - t0) * 1000

print(f"\n[2] FIFO Queue Drain Benchmark ({N:,} items):")
print(f"    list.pop(0)    [O(n^2) total]: {dt_list:7.2f} ms")
print(f"    deque.popleft() [O(n) total]:  {dt_deque:7.2f} ms ({dt_list / max(dt_deque, 0.01):.1f}x faster!)")
▶ Interactive Wasm Lab

Lab 6.3: O(1) LRU Cache (OrderedDict), Prefix Trie, Union-Find & DAG TopologicalSorter

Execute four complete production & interview data structures live: an O(1) OrderedDict LRU cache, a Prefix Trie, a Path-Compressed Union-Find, and graphlib.TopologicalSorter.

from collections import OrderedDict
from graphlib import TopologicalSorter

# 1. Production O(1) LRU Cache using OrderedDict.move_to_end & popitem(last=False)
class LRUCache:
    def __init__(self, capacity: int):
        self.capacity = capacity
        self.store: OrderedDict[str, object] = OrderedDict()

    def get(self, key: str) -> object | None:
        if key not in self.store:
            return None
        self.store.move_to_end(key, last=True)
        return self.store[key]

    def put(self, key: str, value: object) -> None:
        if key in self.store:
            self.store.move_to_end(key, last=True)
        self.store[key] = value
        if len(self.store) > self.capacity:
            self.store.popitem(last=False)

cache = LRUCache(2)
cache.put("a", 1); cache.put("b", 2); _ = cache.get("a"); cache.put("c", 3)
print("[1] O(1) OrderedDict LRU Cache Surviving Keys:", list(cache.store.keys()))

# 2. Prefix Tree (Trie) for O(L) Prefix Autocomplete
class Trie:
    def __init__(self):
        self.root: dict = {}

    def insert(self, word: str) -> None:
        node = self.root
        for ch in word:
            node = node.setdefault(ch, {})
        node["$"] = word

    def autocomplete(self, prefix: str) -> list[str]:
        node = self.root
        for ch in prefix:
            if ch not in node:
                return []
            node = node[ch]
        results = []
        stack = [node]
        while stack:
            curr = stack.pop()
            if "$" in curr:
                results.append(curr["$"])
            for k, child in curr.items():
                if k != "$":
                    stack.append(child)
        return sorted(results)

trie = Trie()
for w in ["agent", "agentic", "agency", "algorithm", "asyncio"]:
    trie.insert(w)
print("[2] Trie Prefix Autocomplete for 'agen':", trie.autocomplete("agen"))

# 3. Disjoint Set Union (Union-Find) Connected Components
class UnionFind:
    def __init__(self, n: int):
        self.parent = list(range(n))
        self.components = n
    def find(self, x: int) -> int:
        while self.parent[x] != x:
            self.parent[x] = self.parent[self.parent[x]]
            x = self.parent[x]
        return x
    def union(self, a: int, b: int) -> None:
        ra, rb = self.find(a), self.find(b)
        if ra != rb:
            self.parent[rb] = ra
            self.components -= 1

uf = UnionFind(5)
for u, v in [(0, 1), (1, 2), (3, 4)]:
    uf.union(u, v)
print(f"[3] Union-Find Connected Components: {uf.components} (0 & 2 connected? {uf.find(0) == uf.find(2)})")

# 4. Stdlib DAG Topological Sort (graphlib.TopologicalSorter)
ts = TopologicalSorter({"deploy": {"eval", "docker"}, "eval": {"schema"}, "docker": {"schema"}})
print("[4] DAG Topological Execution Order:", list(ts.static_order()))

Frequently Asked Staff Interview Questions (Module 6)

What is the difference between list.sort() and sorted(), or list.reverse() and reversed()? ▸

list.sort(key=..., reverse=...) mutates the list in-place using Timsort (O(n log n) time, O(n) worst-case scratch space) and returns None to remind you no new list was allocated. sorted(iterable, key=..., reverse=...) accepts ANY iterable (including generators, dicts, sets) and returns a brand-new sorted list. Similarly, list.reverse() reverses in-place in O(n) returning None, whereas reversed(seq) returns a zero-copy O(1) reverse iterator.

What is the difference between dict[k], dict.get(k), dict.setdefault(k, default), and collections.defaultdict? ▸

d[k] raises KeyError if k is missing (unless d is a defaultdict, which calls default_factory() and inserts the result). d.get(k, default=None) returns default without mutating the dictionary (even on a defaultdict!). d.setdefault(k, default) returns d[k] if present, or inserts d[k] = default and returns it—useful for one-off grouping, though defaultdict(list) is faster inside loops because it avoids instantiating a new default object on every iteration.

Why should you use str.removeprefix() and str.removesuffix() instead of str.strip()? ▸

str.strip(chars) treats its argument as a SET of individual characters to strip from both ends—so "unhappy_user".strip("un_") unexpectedly strips the trailing "u" or inner characters if matched at the boundary! Added in Python 3.9 (PEP 616), s.removeprefix("un_") and s.removesuffix(".json") remove the exact prefix or suffix substring once.

How does Python’s dict preserve insertion order while remaining O(1) and memory-compact? ▸

Compact Dict (Python 3.6+) splits storage into: (1) dk_indices, a sparse hash table storing only 1-byte to 8-byte integer offsets, and (2) dk_entries, a dense append-only array of 24-byte (hash, key*, value*) structs. Iterating simply scans dk_entries sequentially in insertion order.