Skip to content
Tech Interview Prep
Technical interview guide

Core Data Structures

Lists, tuples, dicts, and sets: their underlying implementations and when each is the right choice.

Minutes to read
3
Practice MCQs
25
Interview Q&A
25
Edition
v3
Editorial status
Reviewed

Scope: Python 3.14; notes distinguish language guarantees from CPython implementation behavior.

Interview Q&A

Treat each question like a live interview question: answer out loud first (structure, assumptions, tradeoffs), then open the model answer to spot gaps and rehearse a tighter follow-up.

Curated: · Written: · Reviewed:

25 questions

Q&A-4

What does tuple immutability guarantee, and what does it not guarantee?

Answer

Short answer

Tuple immutability guarantees one thing: the tuple's slot array is fixed. Once built, a tuple holds the same references, in the same order, at the same length, for its whole life. It does not guarantee that the objects those references point at are immutable. A tuple is an immutable sequence of references, not a deep freeze. t[0] = x always raises; t[0].append(x) succeeds whenever t[0] is a list.

The mechanism, traced

Python
>>> t = ([1, 2], "name")
>>> t[0].append(3)
>>> t
([1, 2, 3], 'name')
>>> t[0] = [9]
TypeError: 'tuple' object does not support item assignment

Walk it the way CPython does. t is a PyTupleObject: a header plus a fixed array of two PyObject * slots. t[0] reads slot 0 and returns the list object: no copy, no wrapper. .append(3) calls list.append on that object, mutating the list's own internal array. The tuple is untouched: slot 0 still holds the same pointer, slot 1 still holds the same string, len(t) is still 2. The second statement is different: t[0] = ... compiles to STORE_SUBSCR, and tuple has no tp_ass_subscript slot, so CPython raises TypeError before evaluating the right-hand side.

The trap that catches people in review:

Python
>>> t = ([1],)
>>> t[0] += [2]
TypeError: 'tuple' object does not support item assignment
>>> t
([1, 2],)

t[0] += [2] is t[0] = t[0].__iadd__([2]). list.__iadd__ mutates in place and returns the list, so the list is already [1, 2] when the store back into slot 0 fails. The exception is real and the mutation is real; code that reads "the tuple didn't change" as "nothing changed" is wrong here.

The boundary that matters: hashability

A tuple's hash is derived from its elements, so a tuple is hashable only if every element is:

Python
>>> hash((1, 2))
-3550055125485641917
>>> hash(([1], 2))
TypeError: unhashable type: 'list'

Two details matter. The check happens at hash() time, not construction time: ([1], 2) is a perfectly valid tuple that simply cannot be hashed. And CPython does not cache a tuple's hash: PyTupleObject has no hash field, so hash(t) recomputes over all n elements on every call, O(n) with n __hash__ calls. str caches its hash in PyASCIIObject.hash, which is why a long string key is cheap on the second lookup and a long tuple key is not: a 1000-element tuple used as a dict key pays 1000 element hashes per lookup. A tuple of ints hashes identically across runs; a tuple of strings does not, because string hashing is salted by PYTHONHASHSEED.

Hashability is also not stability. An object can define __hash__ and still mutate:

Python
class P:
    def __init__(self): self.x = 1
    def __hash__(self): return hash(self.x)

d = {(P(),): "v"}   # hash is stable, p.x is not

The tuple is immutable, the key's hash is well-defined, and the dict entry is still unreachable once p.x changes. Immutability of the container and value-stability of the contents are separate properties.

What immutability buys

  • Fixed shape and length: unpacking is a single UNPACK_SEQUENCE and cannot fail on arity drift. lat, lon = (51.5, -0.12).
  • Stable reference identity: the tuple never silently points at different objects, so it is safe to share across threads (including free-threaded 3.13t builds) without a lock on the tuple itself.
  • Cheap copies: copy.copy(t) is t is True. copy registers tuples as immutable and returns the same object. copy.deepcopy returns the original too when every element is atomic.
  • Compile-time folding: a literal tuple of constants is built once by the compiler and loaded with LOAD_CONST; the empty tuple () is a singleton in CPython.
  • No growth path: a tuple allocates exactly n pointer slots (8 bytes each on a 64-bit CPython 3.12 build). A list carries a separate capacity field and over-allocates, list_resize grows to newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6), so a list is never smaller than the tuple holding the same items.

What it does not buy

  • No deep immutability: nested lists, dicts and sets stay mutable.
  • No thread safety for the contents: the slot array is safe to read concurrently, the list inside it is not.
  • No hashability guarantee, and no protection against a mutable-but-hashable element.
  • No field semantics: t[0] and t[1] are positional. Use namedtuple/NamedTuple for named access, or @dataclass(frozen=True) when you want validation and a FrozenInstanceError (an AttributeError subclass) on assignment: neither deep-freezes fields.
  • No in-place growth: t += (4,) rebinds the name to a new tuple; t2 = t; t += (4,); t is t2 is False.

Tradeoffs

NeedChoiceWhy
Fixed-shape record, immutable fieldstuplefewest slots, hashable, copy-free
Same, with named fieldsnamedtuple / NamedTupletuple layout plus _replace/_asdict
Validation or behavior@dataclass(frozen=True)FrozenInstanceError on assignment; still shallow
Unordered immutable setfrozensethashable, no ordering assumption
True deep immutabilityconvert nested data yourselfPython has no built-in deep freeze

If any field is a list, dict or set, the tuple is the wrong dict key or set member regardless of its own immutability: normalize the nested data first.

Falsifiable summary

Claim: a tuple's sequence of references cannot be replaced, but a referenced object may itself be mutable. The t[0].append(3) / t[0] = [9] trace confirms both halves, and t[0] += [2] shows both can happen in one statement. The common wrong answer ("tuples are immutable, so their contents can't change") fails on the first line of the trace and again on hash(([1], 2)).

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-1

Compare list and deque costs for stacks, queues, and random access.

Answer

Short answer

  • Stack (push/pop at the end): list. append and pop() are amortized O(1).
  • Queue (both ends): collections.deque. appendleft/popleft are O(1); the list equivalents insert(0, x) and pop(0) are O(n) every call.
  • Random access: list. lst[i] is O(1); deque[i] is O(n) in the middle (CPython walks from the nearer end, so O(1) at the ends, O(n/2) worst case).

Mechanism

A CPython list is a contiguous array of PyObject* plus a tracked capacity. append writes one slot; when size == capacity the array is reallocated and copied. The overallocation formula is newsize + (newsize >> 3) + (newsize < 9 ? 3 : 6), so resizes are rare and amortize to O(1) per append. insert(0, x) / pop(0) must memmove every remaining reference one slot: O(n) per call, no amortization.

A deque is a doubly-linked list of blocks, each holding BLOCKLEN = 64 pointers in CPython 3.x. Either end grows by adding a block, so both ends are O(1). The cost is that element i requires walking block-by-block from the nearer end.

Worked trace

Inserting at the front, counting element moves:

Python
lst = []
for i in range(5):
    lst.insert(0, i)
# i=0: [] -> [0]        0 moves
# i=1: [0] -> [1,0]     1 move
# i=2: [1,0] -> [2,1,0] 2 moves
# i=3: 3 moves
# i=4: 4 moves
# total = 0+1+2+3+4 = 10 moves

General n: n(n-1)/2 moves. At n = 100,000 that is 100000·99999/2 = 4,999,950,000 ≈ 5.0e9 reference moves.

The deque version does no moves:

Python
import collections
d = collections.deque()
for i in range(5):
    d.appendleft(i)
# 5 slot writes, 0 moves; at n=100_000 -> 100_000 writes

Timing the two loops (illustrative, 2023 laptop, CPython 3.11): the list loop lands around 1–2 s, the deque loop around 10 ms. A 100–200× gap that widens quadratically with n.

Operationlistdeque
append / pop() rightO(1) amortizedO(1)
appendleft / popleftO(n)O(1)
x[i]O(1)O(n); O(1) at ends
insert(i, v) midO(n)O(n)
x[a:b] sliceO(k)TypeError
Memorycontiguous, ≤ ~12.5% over-alloc64-pointer blocks + block headers

Tradeoffs and failure modes

  • "append is O(1)" is amortized, not worst-case. One append can trigger an O(n) copy; a latency-sensitive path can see that spike.
  • deque has no slicing and slow indexing. d[500_000] in a loop is quadratic. If you need both ends and indexing, use a list with an index offset, or restructure.
  • deque(maxlen=N) silently discards from the opposite end on append: a ring buffer, or a silent data-loss bug if unintended.
  • Thread safety: append/appendleft/popleft are atomic under the GIL, but multi-step queue logic is not; use queue.Queue for blocking producer/consumer.

What changes the decision

  • End-only access → list (better cache locality, less memory).
  • FIFO at volume → deque, or queue.Queue across threads.
  • maxlen ring-buffer semantics → deque.
  • Heavy indexing or slicing → list.
  • Large uniform numeric data → neither; array or NumPy.

Benchmark your real mix of end-operations vs. indexing: the crossover depends on that ratio, not on n alone.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-22

Defend a container choice for a high-throughput FIFO queue.

Answer

Clarify the problem

Assumptions up front: single process, in-memory, many producers and consumers on threads or an event loop, elements are small (100–500 B), target ~1M ops/sec, and I need O(1) push and pop from opposite ends. If the queue must be shared across processes or survive a crash, the container choice is the wrong lever: I say what replaces it at the end.

The choice: collections.deque

deque is a doubly-linked list of fixed-size blocks (CPython uses 64 slots per block). append() and popleft() are O(1) and never shift or reallocate existing elements. That is the whole argument: FIFO needs cheap removal at the head, and deque is the only stdlib container that gives it without a lock.

The work

Containerpushpop (FIFO side)Failure mode
listamortized O(1) appendO(n) pop(0) shifts all n pointersat n=100k, each pop memmoves ~800 KB
collections.dequeO(1) appendO(1) popleftnone for this workload
queue.QueueO(1) internallyO(1) getlock + condition-variable per op
heapq on a listO(log n)O(log n)wrong structure: orders by priority, not arrival

Correctness demo, runnable:

Python
from collections import deque

q = deque(maxlen=3)
for i in range(5):
    q.append(i)
print(list(q))          # bounded: drops oldest

fifo = deque()
fifo.extend([1, 2, 3])
print(fifo.popleft(), fifo.popleft(), len(fifo))

Trace: appends 0,1,2 fill the deque; appending 3 evicts 0 → [1,2,3]; appending 4 evicts 1 → [2,3,4]. So the first print is [2, 3, 4]. extend gives [1,2,3]; first popleft returns 1 leaving [2,3]; second returns 2 leaving [3]; len is 1. Second print: 1 2 1.

Representative timings (CPython 3.12, single thread, x86-64; machine-dependent):

  • deque append+popleft pair: ~60–80 ns → ~12–15M ops/sec.
  • list pop(0): grows with n. At n=100k, ~50–100 µs per pop (800 KB memmove) → ~10k ops/sec, a ~1000x gap that widens with depth.
  • queue.Queue: ~500 ns–1 µs/op uncontended → ~1–2M ops/sec, worse under contention.

deque is the only candidate that clears 1M ops/sec with headroom.

Details that decide follow-ups

  • deque(maxlen=N) bounds memory with O(1) drop-oldest: backpressure by truncation, but it silently discards; only if loss is acceptable.
  • append/popleft are individually atomic under the GIL, so a single-producer/single-consumer handoff needs no lock. queue.Queue is still right when consumers must block: its condition variables are the feature.
  • Indexing the middle is O(n/2); irrelevant for FIFO, a real constraint if the design drifts to peek-by-index.

What changes the decision

  • Cross-process consumers → multiprocessing.Queue; pickling dominates, container choice is moot.
  • Durability → a WAL or Redis LPUSH/BRPOP, not an in-memory structure.
  • Blocking/fair wakeup across many threads → queue.Queue (or queue.SimpleQueue for a lighter C implementation without task tracking).
  • Sustained >5M ops/sec with real concurrency → the GIL caps any Python-level queue; move to a native ring buffer or a broker.

Test plan

Benchmark at realistic element size and queue depth (the list penalty only appears at depth), and assert the contract: FIFO order under concurrent producers, bounded memory with maxlen, no unbounded growth when push outruns pop.

Bottom line: collections.deque. O(1) at both ends, no shifting, no lock tax; escalate to queue.Queue only for blocking semantics, and out of Python for durability or multi-process scale.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-3

When would you choose `sort()` over `sorted()`, and how does stability affect the design?

Answer

The 90-second answer

sorted() is a builtin: it accepts any iterable and returns a new list. list.sort() is a method: it reorders the list in place and returns None. Reach for sort() when you own the list, no other reference to it exists, and you want to avoid a second allocation. Reach for sorted() when the input isn't a list (a generator, a dict, a tuple, a set, a dict_keys view) when the caller's data has to survive the call, or when you want the sort as an expression, e.g. top = sorted(rows, key=itemgetter(1))[:10].

Both run the same algorithm: Timsort, in CPython's listobject.c. Worst case O(n log n) comparisons; O(n) when the input is already sorted or consists of a few ascending runs. Both are stable, and stability is a documented guarantee, the Sorting HOW TO states that sorts are guaranteed stable, not an accident of the implementation. That guarantee is the design tool: elements that compare equal keep their prior relative order, so you can sort in passes.

Stability as a design tool

Multi-pass sorting is the classic use. Sort by the least significant key first, then by the more significant one; the second pass leaves ties in the order the first pass produced. It's equivalent to a composite tuple key, but sometimes the passes read better: for instance when the secondary key is expensive and you want to compute it once.

Python
records = [("b", 2), ("a", 1), ("b", 1), ("a", 2)]

by_value = sorted(records, key=lambda r: r[1])
# [('a', 1), ('b', 1), ('b', 2), ('a', 2)]
result = sorted(by_value, key=lambda r: r[0])
# [('a', 1), ('a', 2), ('b', 1), ('b', 2)]

assert result == sorted(records, key=lambda r: (r[0], r[1]))

Trace the first pass: values are 2, 1, 1, 2. The two records with value 1 are ("a", 1) then ("b", 1) in input order, and stability keeps them that way; the value-2 records keep ("b", 2) before ("a", 2). The second pass groups by letter, and within each letter the value order from pass one survives. The assertion holds.

Stability also pays off when the unkeyed order already carries meaning. If rows arrive in timestamp order and you now sort by user id, ties stay in timestamp order for free: no composite key needed.

The failure mode

sort() returns None on purpose, matching list.append and dict.update: the return value signals mutation, so you can't chain it.

Python
values = [3, 1, 2]
result = values.sort()
print(result)   # None
print(values)   # [1, 2, 3]

Assigning or chaining the result is the bug. If you need an expression, that's sorted().

Cost

list.sort()sorted()
Inputlist onlyany iterable
Allocationnonenew list, 8 bytes per element of pointer array
ReturnsNonenew list
Original orderdestroyedpreserved
Temp memoryup to n/2 pointers (Timsort merge buffer)result + merge buffer

The extra list is a pointer array, not a copy of the objects. For 10M ints on 64-bit CPython, sys.getsizeof gives ~80 MB for the list of pointers and ~28 bytes per distinct int object, so the objects dominate and sorted() adds roughly 80 MB on top of ~360 MB: about 20%, not a doubling. The real reason to prefer sorted() is correctness: if the list is shared, an in-place sort is a side effect on every other holder of that reference.

What changes the decision

  • Input is a generator or stream: sorted() is the only option; it materialises the list.
  • Memory-constrained, list is local and disposable: sort().
  • Top-k on large data: heapq.nsmallest(k, it, key=...) is O(n log k) and skips the full sort.
  • Porting the assumption: Java's Arrays.sort on primitives is dual-pivot quicksort and not stable, while Collections.sort is. Check the guarantee before relying on it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-21

Explain the comparison semantics of sequences and sets without claiming a total order.

Answer

Short answer

In Python 3, sequences and sets have fundamentally different comparison semantics. Sequences (list, tuple, str, range) support both == and the full set of relational operators, with < defined lexicographically: compare element by element, first difference decides, shorter-is-smaller if one is a prefix of the other. Sets support == as element-identity and </<=/>/>= as proper subset / subset / superset: a partial order, since two sets can be incomparable. Neither semantics orders everything: cross-type comparisons like [1, 2] < (1, 3) raise TypeError.

Sequences: lexicographic, positional

Python
[1, 2] < [1, 3]        # True — first differing index decides
[1, 2] < [1, 2, 0]      # True — prefix is smaller
[2] < [1, 99]           # False — 2 > 1 at index 0, 99 never examined
[1, 2] == (1, 2)        # False — different types never equal
[1, 2] < (1, 3)         # TypeError: '<' not supported between 'list' and 'tuple'

The mechanism is the one documented in the language reference: compare items pairwise until a pair differs, then return that pair's comparison result; if one sequence runs out first, the shorter one is smaller. == additionally requires equal lengths. The comparison short-circuits, [2] < [1, 99] never looks at the 99, so cost is O(min(len(a), len(b))) for < and O(n) worst case for ==.

This ordering is well-defined within one sequence type, which is why sorted([[1,2], [1,1], [0,9]]) works and yields [[0, 9], [1, 1], [1, 2]]. The catch is that it only holds when elements are pairwise comparable: [[1], ['a']] sorted raises TypeError at the first int vs str comparison.

Sets: subset relations, partial order

Python
{1, 2, 3} == {3, 1, 2}   # True — order and multiplicity ignored
{1, 2} <= {1, 2, 3}      # True — subset
{1, 2} < {1, 2, 3}       # True — proper subset
{1, 2} < {1, 3}          # False
{1, 3} < {1, 2}          # False — incomparable

{1, 2} and {1, 3} are neither subsets nor supersets of each other, so < returns False both ways. Antisymmetry does hold, a <= b and b <= a implies a == b, so the subset relation is a partial order in the mathematical sense, not a broken one.

Set == costs O(len(smaller)) on average: each element of one set is looked up by hash in the other, with a length check first. That's why set(a) == set(b) beats sorted(a) == sorted(b) (O(n log n)) for order-insensitive equality on large inputs.

The trap an interviewer is probing

Reading a < b on sets as "a is smaller" is the classic bug. len(a) < len(b) is a different predicate from a < b: {5} < {1, 2} is False even though {5} has fewer elements. Conversely, people assume lists can't be ordered at all: they can, lexicographically, and max([[1, 2], [1, 3]]) returns [1, 3].

Two more asymmetries worth naming:

  • frozenset({1}) == {1} is True: set equality ignores the concrete type, unlike sequences where [1] != (1,).
  • Set elements must be hashable, so {[1]} raises TypeError: unhashable type: 'list' at construction: the comparison question never arises. Sequence elements need no such constraint; comparability is only checked lazily, element by element.

Summary table

Sequences (list, tuple)Sets (set, frozenset)
==positional, length-sensitivesame elements, order/multiplicity ignored
<lexicographic, well-defined within a typeproper subset, partial
Incomparable pairscross-type, or mismatched element typesany two sets neither containing the other
Cost of ==O(n), short-circuitsO(len(smaller)) average

If the interviewer pushes toward functools.total_ordering or NumPy arrays: functools.total_ordering is an opt-in decorator that fills out ordering methods on a class you define. NumPy is a different animal entirely: == and < on arrays are element-wise and return boolean arrays, not a single bool, so np.array([1, 2]) < np.array([1, 3]) gives array([False, True]). Neither follows the built-in container semantics above. The built-in set semantics deliberately stop at subset relations, because any full ordering over unordered collections would be arbitrary.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-2

Explain aliasing versus copying for nested Python lists and how you would define ownership.

Answer

Short answer

Assignment in Python binds a name to an object; it never copies. b = a makes b another name for the same list, so any in-place mutation through either name is visible through the other. A shallow copy (a.copy(), a[:], list(a), copy.copy(a)) allocates a new outer list but copies only the references, so the inner lists are still shared and nested mutation still leaks. copy.deepcopy(a) recursively rebuilds every container, giving full independence at a cost proportional to the whole object graph.

Ownership is not a language feature; it is a documented contract: who may mutate this object, through when, and who must copy before mutating. I make it explicit at the API boundary: a constructor copies its inputs, getters return copies or read-only views, and any intentional sharing is stated in the docstring.

Mechanism, with a trace

Python
import copy

a = [[1, 2], [3, 4]]
b = a                      # alias, not a copy
b is a                     # True
b.append([5])
a                          # [[1, 2], [3, 4], [5]]   a changed too

c = a.copy()               # same as a[:] and list(a)
c is a                     # False
c[0] is a[0]               # True   inner list still shared
c[0].append(99)
a                          # [[1, 99, 2], [3, 4], [5]]

d = copy.deepcopy(a)
d[0] is a[0]               # False
d[0].append(7)
a                          # [[1, 99, 2], [3, 4], [5]]   unchanged
d                          # [[1, 99, 2, 7], [3, 4], [5]]

deepcopy also terminates on cycles because it keeps a memo dict keyed by id() of every object it has already copied:

Python
x = []
x.append(x)
y = copy.deepcopy(x)       # no infinite recursion
y[0] is y                  # True

What it costs

  • a.copy() allocates one list of n pointers: O(n) at the top level only. On 64-bit CPython 3.12, sys.getsizeof([0] * 1000) is 8056 bytes: a 56-byte list header plus 8 bytes per pointer.
  • copy.deepcopy visits every element and does one memo lookup per object, so it is O(total elements), not O(top-level length). Atomic types (int, str, float, bytes, bool, None) are returned as-is, so a 1000×1000 list of ints allocates 1001 new lists and shares the ints: 10^6 element visits against 10^3 pointer copies for the shallow copy, roughly 1000× the work.
  • sys.getrefcount(a) returns the reference count plus one for the temporary argument; it is how I detect an unexpected alias in a test.

Defining ownership

Python
class Grid:
    def __init__(self, rows):
        self._rows = [list(r) for r in rows]   # own a private copy

    def rows(self):
        return tuple(self._rows)               # read-only outer view

tuple(self._rows) is still shallow: callers hold references to the inner lists. If those must be protected too, return tuple(tuple(r) for r in self._rows), or document that rows are shared. For dicts, types.MappingProxyType(d) gives a live read-only view without copying.

Rules I apply and write down: the constructor takes ownership of mutable arguments unless the docstring says otherwise; getters return copies or read-only views; intentional sharing is named at the API ("the returned list aliases internal state; do not mutate"); and anything crossing a thread, process, cache or plugin boundary is copied at that boundary.

Failure modes and tradeoffs

  • Snapshot bug: b = a is treated as a snapshot, a helper calls b.sort(), and a is silently reordered. Detect it by asserting on id() of the inner objects, or make the shared object a tuple so the bug cannot compile into existence.
  • Default mutable argument: def add(item, acc=[]) creates acc once at def time, so every call without an explicit list shares one list.
  • Dict views: d.keys() aliases d; mutating d while iterating raises RuntimeError: dictionary changed size during iteration.
  • Module-level state: sys.argv is a plain list, so mutating it changes what every other importer sees.

Copying everything defensively is safe but pays O(n) per call and adds GC pressure; sharing everything is free but couples modules. The middle ground is a shallow copy when the elements are immutable, sharing children is then harmless, and a deep copy only when nested mutables must diverge. Tests should assert on identity, not equality: == cannot tell an alias from an equal copy.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-17

Contrast shallow copy, deep copy, and deliberate reconstruction of an object graph.

Answer

What a strong candidate says first

"Copy" is not one operation. The three options differ on a single axis: how much of the object graph is shared with the source. A shallow copy allocates one new container and shares every child; a deep copy allocates a new object for every reachable node; deliberate reconstruction allocates exactly the nodes you name and shares the rest. My default in production code is reconstruction, because it makes the sharing decision explicit and testable; copy.deepcopy is the fallback when the graph's shape is unknown.

Assumptions: CPython 3.12, the copy module, plain Python objects (no C-extension types with custom copy semantics).

The graph

Python
import copy

class Profile:
    def __init__(self, tags):
        self.tags = tags
    def __repr__(self):
        return f"Profile(tags={self.tags})"

src = {"user": Profile(["admin"]), "meta": {"version": 2}}

Three levels: dict → Profile → list, plus a nested dict. Two mutable leaves (tags, meta).

Shallow copy: copy.copy

Python
sh = copy.copy(src)
sh["user"].tags.append("debug")
print(src["user"].tags)   # ['admin', 'debug']

Trace: copy.copy(src) returns a new dict, so sh is not src is True, but sh["user"] is src["user"] and sh["meta"] is src["meta"] are both True. The append mutates the one shared list, so the source sees it. Cost is one allocation and O(top-level keys) pointer copies. Failure mode: any nested mutation leaks. sh["meta"]["version"] = 3 also changes src.

Deep copy: copy.deepcopy

Python
dp = copy.deepcopy(src)
dp["user"].tags.append("debug")
print(src["user"].tags)   # ['admin']

Mechanism: deepcopy walks the graph depth-first, keeping a memo dict keyed by id(original) → copy. That memo is why cycles and shared sub-objects terminate and stay shared: a = []; a.append(a); copy.deepcopy(a) returns a self-referential list instead of recursing forever. Classes can override with __deepcopy__(self, memo) or __copy__.

Cost: one allocation per reachable object plus a memo entry each. Illustrative, not measured here: a 100k-node graph is 100k allocations and tens to hundreds of milliseconds on a laptop, against microseconds for the shallow copy of the same top-level dict.

Failure mode: it copies things that must not be copied. copy.deepcopy(threading.Lock()) raises TypeError: cannot pickle '_thread.lock' object, because with no __deepcopy__ it falls back to __reduce_ex__/pickle. Open sockets, DB connections and file handles hit the same wall or silently produce a broken duplicate.

Deliberate reconstruction

Python
def clone_profile(p, deep_tags=True):
    return Profile(list(p.tags) if deep_tags else p.tags)

snapshot = {
    "user": clone_profile(src["user"]),
    "meta": dict(src["meta"]),
}

You name each field and decide. snapshot["user"] is not src["user"], and snapshot["user"].tags is not src["user"].tags because of the list(...); snapshot["meta"] is not src["meta"] is a new dict, while the int 2 inside is shared: harmless, ints are immutable.

Cost is O(fields you copy). Failure mode: a field added later that the reconstructor doesn't handle silently reverts to shallow semantics, and the bug stays invisible until someone mutates it. Python 3.13's copy.replace and dataclasses.replace are the standard-library versions of this for dataclasses and namedtuples.

Comparison

New top-levelNested mutablesCostFailure mode
copy.copyyessharedO(top-level keys)nested mutation leaks across graphs
copy.deepcopyyesduplicatedO(all reachable objects) + memocopies uncopyable resources; slow; over-duplicates
Reconstructionyesyour choiceO(fields you copy)missed field → accidental sharing

Decision rule

  • Unknown graph shape, need full isolation → deepcopy, accept the cost.
  • One-level snapshot, children treated as immutable → shallow copy, and write that contract down.
  • Hot path, known schema, or graph holds locks/connections → reconstruct explicitly.

Two things flip it: a DAG with heavy sharing (deepcopy's memo preserves the sharing; naive reconstruction fans it out and can blow up memory), and external resources (deepcopy is off the table regardless of speed).

Testing

Assert isolation, not just equality: mutate every mutable leaf of the copy, assert the source is unchanged, and assert identity where sharing is intended (snapshot["meta"] is not src["meta"], but a shared read-only buffer is the same object). That test fails the moment someone adds a field the reconstructor forgot.

Interview signal

Name the memo/cycle behaviour of deepcopy and the aliasing failure of shallow copy with a trace, then land on: reconstruction is the default in real systems, deepcopy is the fallback for graphs you don't control. The weak answer says "deep copy copies everything" and stops there.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-18

Diagnose the repeated-row aliasing bug created by sequence multiplication.

Answer

What you say first

The outer * rows copies references, not rows. [[0] * cols] * rows builds one row list and stores that same object at every index, so any mutation through an element is visible from every row. The inner [0] * cols is fine: it repeats an immutable int. Fix it with a comprehension that allocates a fresh row per index: [[0] * cols for _ in range(rows)].

Reproduce and trace it

Python
rows, cols = 3, 4
matrix = [[0] * cols] * rows
matrix[0][0] = 9
print(matrix)
# [[9, 0, 0, 0], [9, 0, 0, 0], [9, 0, 0, 0]]

Step by step, the way CPython runs it:

  1. [0] allocates a new list holding one pointer to the cached int 0.
  2. [0] * 4 allocates a new list of length 4, four pointers to that same cached 0. Call this object R.
  3. [R] * 3 allocates a new list of length 3 holding three pointers to R. No copy of R is made.
  4. matrix[0][0] = 9 evaluates matrix[0] → R, then sets R[0] = 9. R's slot 0 now points to the int 9.
  5. print walks the outer list, finds R three times, and prints the same mutated row three times.

Confirm the aliasing directly:

Python
matrix[0] is matrix[1] is matrix[2]   # True
len(set(map(id, matrix)))             # 1, not 3

The diagnostic asymmetry

OperationWhat it touchesVisible in other rows?
matrix[1] = [0]*colsrebinds one outer slotno
matrix[1][2] = 9mutates the shared row objectyes
matrix[1].append(9)mutates the shared row objectyes

Assignment to an outer slot replaces a reference; mutation through an element reaches the one object every slot points at. That split is the fastest way to tell an aliasing bug from a legitimate rebind.

What it costs

On 64-bit CPython 3.12, sys.getsizeof([]) is 56 bytes and each element pointer adds 8. For rows=3, cols=4:

  • Buggy: outer list 56 + 3*8 = 80 bytes, plus one row 56 + 4*8 = 88 bytes → 168 bytes.
  • Correct: outer 80 bytes, plus three rows 3 * 88 = 264 → 344 bytes.

At rows=cols=1000 the gap is structural: the buggy form holds one row (56 + 8000 = 8056 bytes) plus the outer list (8056 bytes) ≈ 16 KB, while the comprehension holds 1000 rows ≈ 8 MB. Both are O(rows × cols) time, so there is no performance argument for the buggy form: only the memory you didn't intend to share.

Fix

Python
matrix = [[0] * cols for _ in range(rows)]
matrix[0][0] = 9
print(matrix)
# [[9, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]
matrix[0] is matrix[1]   # False

The comprehension evaluates [0] * cols once per iteration, producing rows distinct row objects. For deeper nesting, nest comprehensions or reach for copy.deepcopy when cycles or arbitrary depth make explicit construction impractical.

Regression test

Python
def test_matrix_rows_independent():
    m = build_matrix(3, 4)
    m[0][0] = 9
    assert all(r[0] == 0 for r in m[1:])

This fails against [[0]*cols]*rows and passes against the comprehension: one line covering the whole class of bug.

When aliasing is intended

If the rows are genuinely meant to be the same object (a shared sentinel row, for instance), the aliasing is correct and the comprehension would be wrong. Even then, mutation through an index is a hazard, so make the intent explicit with a comment or an immutable row type. The decision hinges on element mutability and intended ownership, not on the * operator itself: seq * n is safe when the repeated element is immutable (int, str, tuple of immutables) and a bug when it is mutable or when you later mutate through it.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-19

Why are mutable default arguments persistent, and when might that persistence be intentional?

Answer

Short answer

A default argument is evaluated once, at def execution time, and stored on the function object as func.__defaults__. Every call that omits that argument reuses the same object, so if it's mutable (list, dict, set, most class instances), mutations made during one call are visible on the next call. That's the persistence: it's not a copy per call, it's one shared object bound into the function's metadata.

Show the mechanism

Python
def append_to(item, target=[]):
    target.append(item)
    return target

append_to(1)   # [1]
append_to(2)   # [1, 2]  <- same list object, not a fresh []
append_to(3)   # [1, 2, 3]

append_to.__defaults__   # ([1, 2, 3],) — the accumulated list lives here

You can verify it's aliasing, not magic:

Python
a = append_to(4)
b = append_to(5)
a is b            # True — one object returned every time
a is append_to.__defaults__[0]   # True

Contrast with an immutable default:

Python
def greet(name, prefix="Hi"):
    prefix = prefix + "!"   # rebinds the local name; the str object can't be mutated
    return f"{prefix} {name}"

Strings can't be mutated in place, so rebinding the local name never touches __defaults__. The bug only exists when the default is mutated in place.

The standard fix, and its cost

Python
def append_to(item, target=None):
    if target is None:
        target = []
    target.append(item)
    return target

The None sentinel costs one comparison and one allocation per call: negligible, which is why it's the idiomatic default. (A bool(target) truthiness check is wrong: it breaks for legitimately empty-but-not-None containers passed explicitly.)

When persistence is intentional

The shared object is a feature when you want call-to-call state without a class or global:

  1. Memoization / caching.
Python
def fib(n, _cache={}):
    if n in _cache:
        return _cache[n]
    _cache[n] = n if n < 2 else fib(n - 1) + fib(n - 2)
    return _cache[n]

This is O(1) lookup per call and survives across calls by design. Tradeoffs to state out loud: the cache is invisible to callers (can't be cleared or inspected via a named attribute unless you expose it), it's not thread-safe without a lock (CPython dict setdefault/assignment are individually atomic under the GIL, but a check-then-set sequence is not), and it bypasses functools.lru_cache, which gives you bounded size, cache_info(), and cache_clear() for free. In real code I'd reach for @lru_cache(maxsize=None) first and reserve the mutable-default trick for hot paths where even the decorator's wrapper overhead matters.

  1. Accumulators / registries.
Python
def register(name, _registry=[]):
    _registry.append(name)
    return len(_registry)
  1. Sentinel-free "call with previous state" patterns in quick scripts or notebooks.

Decision rule

  • Default should be fresh per call → use None sentinel. This is the correct choice whenever callers might pass their own container, because returning a caller's list mutated in place plus a shared default is the worst of both worlds.
  • Default should be shared state → keep the mutable default, but document it (_cache={} naming convention, docstring note) and consider whether a closure, functools.lru_cache, or a small class is clearer. A class with __init__ state is more discoverable and testable; the mutable default wins mainly on brevity.

What would change the decision

  • Concurrency: shared mutable default across threads needs locking or lru_cache's internal handling; under free-threaded Python builds the atomicity assumptions weaken further.
  • Testability: hidden state in __defaults__ makes tests order-dependent; expose the cache or inject it as a parameter.
  • Serialization/pickling: functions with large accumulated defaults are a debugging trap. State hides in __defaults__ rather than in any named attribute.

Related aliasing trap worth naming

The same one-object-many-references mechanism appears in sequence repetition: [[0] * n] * m creates m references to one inner list. Mutating grid[0][0] changes every row. The fix is [[0] * n for _ in range(m)], which re-evaluates the inner expression per row. Same root cause: the expression builds references, not copies.

Interview follow-ups I'd expect

  • "When exactly is the default evaluated?": once, when the def statement executes (e.g., each time a def inside a loop runs, a fresh default object is created).
  • "How would you reset the state?": func.__defaults__ = (new_obj,), or better, restructure so state is explicit.
  • "Is this Python-specific?": similar late-binding surprises exist elsewhere (JavaScript var in closures pre-let); the general lesson is: distinguish binding time from call time.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-20

How do truthiness checks differ from sentinel checks in API design?

Answer

Truthiness vs. sentinel checks in API design

The 90-second answer. The two checks answer different questions. if not x: asks "is this value falsy?": it collapses "absent" and "empty" into one branch. if x is None: asks "is this the specific object I chose to mean absent?": it keeps them apart. The question that decides it in API design is: can a caller legitimately pass an empty-but-valid value and expect it to be honored? If yes, you need a sentinel. If the contract genuinely says "empty means take the default," truthiness is fine and simpler. The bug is never truthiness itself; it's using truthiness as a proxy for "was an argument passed?"

Mechanism. not x goes through the __bool__ protocol, falling back to __len__ when __bool__ isn't defined. Both are user-overridable, so the cost and the semantics are whatever the type author decided. For list, dict, set, str, bytes it's an O(1) length check. For a custom type it can be anything, including a scan or a raise. x is None is a pointer comparison against the None singleton: no dispatch, no user code, O(1), and it cannot be confused with 0, 0.0, "", [], {}, False, or Decimal(0), all of which are falsy.

Where they diverge: a worked trace.

Python
def add(x, items=[]):        # default evaluated once, at def time
    items.append(x)
    return items

add(1)          # [1]
add(2)          # [1, 2]   same list object as the first call
add(3, [])      # [3]      caller's own list

Trace it the way CPython does. The default expression [] is evaluated once, when the def statement executes, and that one list object is bound to items for every call that omits the argument. add(1) appends into it and returns it; add(2) appends into the same object, so the caller sees [1, 2]. add(3, []) passes a different list, so it returns [3]. Two callers who never intended to share state now do.

Now the truthiness version:

Python
def add(x, items=None):
    if not items:            # truthiness
        items = []
    items.append(x)
    return items

mine = []
add(1, mine)    # returns [1]
mine            # []        caller's list was discarded, not filled

add(1, mine): mine is [], so not items is True, and the function throws away the caller's list and allocates a fresh one. mine is still [] after the call. The caller asked to append into their own container and got a silent no-op on it. That's the divergence: the empty list is a valid, distinct intent, and truthiness erased it.

The sentinel version:

Python
def add(x, items=None):
    if items is None:        # sentinel
        items = []
    items.append(x)
    return items

mine = []
add(1, mine)    # returns [1]
mine            # [1]       caller's list mutated in place

Now items is None is False for mine, so the caller's list is mutated in place.

Named cases where this bites. dict.get(key) returns None for both a missing key and a key explicitly mapped to None; use key in d or d.get(key, _MISSING) with _MISSING = object(). os.environ.get("X") can't tell unset from "". In JSON, {"timeout": null} and {} both give None from obj.get("timeout"). argparse solves it with default=argparse.SUPPRESS, which leaves the attribute unset entirely; dataclasses uses dataclasses.MISSING; inspect uses inspect.Parameter.empty. All three are module-private sentinels, not None.

Where truthiness actively breaks. A numpy array with more than one element raises ValueError: The truth value of an array with more than one element is ambiguous on if not arr:. A pandas.DataFrame raises ValueError: The truth value of a DataFrame is ambiguous. Generators are always truthy, so if not gen: never fires even for an exhausted generator. And "".split(",") returns [''], not [], a truthy one-element list, so if not parts: misses the empty-input case entirely.

Concernif not x:if x is None:
Distinguishes empty from absentNoYes
Mechanism__bool__, falling back to __len__pointer compare against the None singleton
CostO(1) for built-in containers; arbitrary for custom typesO(1), no dispatch
Can raiseYes: numpy array, pandas DataFrameNo
Falsy non-empty values misread as absent0, 0.0, "", [], {}, False, Decimal(0)n/a
Cost of the sentineln/aNone can't be passed as a real value

When truthiness is right. When the contract is "empty and absent mean the same thing" (a filter list, a batch size, a config override) if not values: return [] is correct and simpler. Document it and move on.

Decision rule. Ask: can "empty" be a valid, distinct caller intent? Yes → sentinel (None if None isn't a legal value, otherwise a module-private object()), and allocate mutable defaults inside the body. No → truthiness, documented.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-6

How does membership testing time complexity differ across standard lists, sets, and sorted lists maintained via bisect?

Answer

Short answer

Membership testing (item in container) is:

  • $O(N)$ on standard unsorted list: requires a sequential scan evaluating equality item by item until a match is found or the list terminates.
  • Average $O(1)$, worst-case $O(N)$ on set: hashes the target item and probes an open-addressed hash table, resolving hash collisions via equality checks.
  • $O(\log N)$ comparisons on a sorted list using bisect.bisect_left: repeatedly halves the search space via index arithmetic, followed by a single equality check at the resulting index.

Concrete mechanisms and traces

1. Standard list (in operator)

item in lst invokes lst.__contains__(item). Because an arbitrary list has no ordering guarantees, Python performs a linear sweep from index 0 to len(lst) - 1:

Python
def linear_contains(lst, target):
    for element in lst:
        if element is target or element == target:
            return True
    return False

Every lookup tests against up to $N$ elements. Best case is $O(1)$ (target is at index 0), but average and worst-case search costs are $\frac{N}{2}$ and $N$ operations.

2. Set lookup (in operator)

set is an open-addressed hash table. target in s computes hash(target), maps that hash to a bucket index modulo table capacity, and inspects the entry:

  1. If the bucket is empty, returns False immediately.
  2. If occupied, checks target is entry or target == entry. If equality holds, returns True.
  3. If unequal (a hash collision), set follows a pseudo-random probe sequence until finding a match or an empty slot.

Under healthy load factors, probe sequences terminate in 1–2 steps, giving average $O(1)$ time. If an adversary forces catastrophic hash collisions, lookup degrades to $O(N)$ comparisons.

3. Bisect-maintained sorted list

item in sorted_lst cannot use the native in keyword for logarithmic lookup because Python's list.__contains__ always executes the linear scan. Instead, you binary search with bisect:

Python
import bisect

def binary_contains(sorted_lst, target):
    idx = bisect.bisect_left(sorted_lst, target)
    return idx < len(sorted_lst) and sorted_lst[idx] == target

bisect_left performs $\lfloor\log_2 N\rfloor + 1$ iterations, dividing the index interval $[lo, hi)$ in half at each step. Once idx is returned, a single equality check confirms whether the item is present.

Comparison and Trade-offs

Container StrategyMembership Cost (Avg)Membership Cost (Worst)Memory Overhead per ElementInsertion Cost
Unsorted list$O(N)$$O(N)$~8 bytes (pointer array)$O(1)$ amortized append
set$O(1)$$O(N)$~32 bytes (hash table entries)$O(1)$ amortized add
Sorted list + bisect$O(\log N)$$O(\log N)$~8 bytes (pointer array)$O(N)$ (requires shifting elements)

Failure modes and engineering decisions

  • Calling in on a sorted list: A common production bug is sorting a list and running if x in sorted_list. This still runs in $O(N)$ time because list.__contains__ does not know the sequence is ordered.
  • Unhashable items: set requires items to implement __hash__ and maintain equality invariants. If elements are unhashable (e.g., dicts, sublists) or have non-static hashes, set fails with TypeError: unhashable type. Bisect requires items to support strict weak ordering (<), avoiding the hashability requirement entirely.
  • Write-heavy workloads: While bisect provides $O(\log N)$ read lookup, inserting via bisect.insort is $O(N)$ because inserting into a contiguous C-array requires shifting subsequent pointers with memmove. If mutations are frequent, set dominates with $O(1)$ insertions.

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-16

How do you reason about average and worst-case membership cost?

Answer

The 90-second answer

Membership cost is the cost of x in coll. For a hash table it is O(1) on average and O(n) worst case, and the whole gap comes down to two variables: the load factor α = entries / slots, and whether the hash function spreads keys uniformly. Average cost is a property of the hash distribution, not of the container: a set with a bad __hash__ is a linked list wearing a hash table's clothes. Worst case is O(n) when keys pile into one probe chain; the realistic triggers are adversarial keys, a degenerate __hash__/__eq__ pair, or a key mutated after insertion. When you need a guarantee rather than an average, a balanced tree gives O(log n) unconditionally.

The table

StructureAverageWorstMechanism
Python set / dictO(1)O(n)open addressing, resizes at α = 3/5
Java HashMapO(1)O(log n) since Java 8bin treeifies at 8 entries
std::unordered_mapO(1)O(n)separate chaining
std::map, Java TreeMap, sortedcontainersO(log n)O(log n)red-black tree
sorted array + bisectO(log n)O(log n)binary search, no hashing
unsorted listO(n)O(n)linear scan
Bloom filterO(k)O(k)k probes; false positives, never false negatives

Why the average is O(1)

Under uniform hashing, the expected probes for a miss is ≈ 1/(1−α) and for a hit ≈ (1/α)·ln(1/(1−α)). CPython's set resizes when fill*5 >= mask*3, so a 1M-element set sits in a 2^21 = 2,097,152-slot table: α = 1e6/2.097e6 ≈ 0.48. That gives ≈ 1.9 probes for a miss and ≈ 1.4 for a hit: constants that do not grow with n. Each probe is a hash, a pointer dereference and an equality check. Measured on a typical machine, x in s over a 1M-int set is ~40–60 ns; x in list_of_1M is ~10 ms. Five orders of magnitude, which is why "use a set" is usually the right first answer.

A worked trace of the worst case

Python
class Bad:
    eq_calls = 0
    def __init__(self, user_id, payload):
        self.user_id = user_id
        self.payload = payload
    def __hash__(self):
        return 42                      # every object collides
    def __eq__(self, other):
        Bad.eq_calls += 1
        return self.payload == other.payload

s = {Bad(i, "x" * 1000) for i in range(1000)}
Bad.eq_calls = 0
print(Bad(-1, "y" * 1000) in s, Bad.eq_calls)

Output: False 1000.

Trace: every object hashes to 42, so all 1000 occupy one probe chain. Building the set already cost 0+1+…+999 = 499,500 __eq__ calls. The lookup for an absent key walks the entire chain (1000 __eq__ calls, each comparing two 1000-character strings) then hits an empty slot and returns False. Membership here is O(n·m): n chain length, m payload comparison. Hashing on user_id instead collapses it back to O(1).

The three triggers

  1. Adversarial keys. An attacker who knows the hash function crafts keys with identical hashes and turns your O(1) set into an O(n) list: hash-flooding DoS. Python 3.3+ randomizes str/bytes hashes per process (PYTHONHASHSEED); Java 8 treeifies bins. Both are direct responses to this. Randomization makes hashes non-reproducible across runs, so never persist hash-derived ordering.
  2. Degenerate __hash__. The trace above. Silent, and it survives code review because the class looks fine.
  3. Mutable keys. Mutate a field that __eq__ reads after insertion and the object hashes to a different slot than it was stored in: it becomes unfindable. That is a correctness bug, not a performance one.

Choosing between them

  • p99 budget you cannot blow: a tree's guaranteed O(log n) beats a hash table's average O(1). At n = 10^6, log₂ n ≈ 20 comparisons, predictable every time.
  • User-supplied keys in a long-lived service: randomized hashing or a tree.
  • Range queries or ordered iteration: tree or sorted array. A hash table cannot answer lo <= k < hi at all.
  • Memory: a 1M-element CPython set holds a 2^21-slot table plus 1M boxed int objects; an array('i') of the same values is 4 MB.

Average membership cost is a property of the hash distribution and the load factor; worst case is O(n) when collisions cluster, and the triggers are adversarial keys, degenerate __hash__/__eq__, or mutable keys. Pick a hash table for the average, a balanced tree when you need a guarantee or ordering, and test with your own hash functions before trusting the O(1) label.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-7

Explain how hashing and equality cooperate during dictionary lookup.

Answer

Short answer

A dict lookup is a two-stage filter. hash(key) picks a starting slot and a probe sequence; equality confirms which candidate in that sequence is the key you asked for. Hash narrows, equality decides. It's fast because CPython caches each stored key's 64-bit hash in the entry, so most probes are rejected by one integer compare and never call your __eq__.

The contract

For any type used as a dict key:

  1. a == b implies hash(a) == hash(b). Equal objects must hash equal.
  2. The converse is not required. Unequal objects may share a hash, a collision, and collisions are resolved by equality, not treated as an error.
  3. The hash must not change while the object is a key. That's why list, dict and set are unhashable.

Break rule 1 and lookups fail silently: the probe lands in a slot that never holds the key, equality never runs, and you get KeyError for a key you know is in there.

What CPython does for d[k]

dict.__getitem__ reaches lookdict in Objects/dictobject.c. Table size is a power of two, minimum 8 (PyDict_MINSIZE). The probe sequence:

perturb = hash
i = hash & (size - 1)
loop:
    examine slot i
    perturb >>= 5
    i = (i * 5 + perturb + 1) & (size - 1)

At each slot the order is: stored hash equal? then pointer identity? then stored == lookup. The hash compare is one Py_hash_t (64-bit) integer compare; __eq__ is arbitrary user code. That ordering is the design: a good hash makes equality calls rare.

A fresh dict has 8 slots and USABLE_FRACTION(8) = (8 << 1)/3 = 5 usable entries, so the sixth insert resizes to 16. Load factor stays at or below 2/3.

Worked trace

Python
class K:
    def __init__(self, name, h):
        self.name, self.h = name, h
    def __hash__(self):
        return self.h
    def __eq__(self, other):
        print(f"  __eq__: {self.name} == {other.name}")
        return isinstance(other, K) and self.name == other.name
    def __repr__(self):
        return f"K({self.name!r}, h={self.h})"

d = {}
d[K("A", 0)] = "va"
d[K("B", 8)] = "vb"     # 8 & 7 == 0, collides with A
d[K("C", 1)] = "vc"
print(d[K("B", 8)])
print(d[K("E", 8)])

Table size 8, mask 7. Every step below is the loop above with real numbers:

opprobeslotstored hashaction
insert A (h=0)10—empty → store A at 0
insert B (h=8)1000 ≠ 8 → perturb=0, i=(0+0+1)&7=1
21—empty → store B at 1
insert C (h=1)1188 ≠ 1 → perturb=0, i=(5+0+1)&7=6
26—empty → store C at 6
lookup B (h=8)1000 ≠ 8 → i=1
2188 == 8 → __eq__(B, B) → True → "vb"
lookup E (h=8)1000 ≠ 8 → i=1
2188 == 8 → __eq__(B, E) → False → i=6
3611 ≠ 8 → i=7
47—empty → KeyError

Output:

  __eq__: B == B
vb
  __eq__: B == E
Traceback (most recent call last):
  ...
KeyError: K('E', h=8)

The shape matters: the successful lookup cost two probes and one __eq__; the miss cost four probes and still only one __eq__, because the other three slots were rejected on the cached hash alone.

Collisions, identity, NaN

hash(1) == hash(1.0) == hash(True) == 1 and 1 == 1.0 == True, so {1: 'a', 1.0: 'b', True: 'c'} collapses to one entry holding 'c': the first-inserted key object is kept, the value is overwritten. That's the contract working, not a bug.

PyObject_RichCompareBool returns true immediately when the two pointers are identical, so looking up the same object never calls __eq__. Since Python 3.10 hash(float('nan')) is derived from id(), so two NaN objects hash differently and occupy two entries, yet d[nan] still finds the one you inserted, because the identity check fires before __eq__ (and nan != nan would otherwise fail).

Failure modes

  • Persisting hash(s) as a cross-process ID. str/bytes hashing is randomized per process since Python 3.3 (PYTHONHASHSEED), using SipHash-1-3 since 3.11 (SipHash-2-4 in 3.4–3.10). The same string hashes differently next run. Persist the value, or a SHA-256 digest.
  • Hash-flooding DoS is exactly the collision attack; randomization exists because collisions are cheap to manufacture for strings.
  • __eq__ without __hash__ makes the class unhashable: Python 3 sets __hash__ = None.
  • __hash__ from mutable state makes the key unreachable:
Python
class Bad:
    def __init__(self, items):
        self.items = items
    def __eq__(self, other):
        return self.items == other.items
    def __hash__(self):
        return len(self.items)      # trivial on purpose, so the trace is exact

b = Bad([1, 2])
d = {b: "x"}          # hash(b) == 2 → slot 2
b.items.append(3)     # hash(b) == 3 now
b in d                # False
d[b]                  # KeyError

The insert probed slot 2 & 7 = 2 and stored there. The lookup probes 3 & 7 = 3, finds it empty, and stops. The entry at slot 2 is never examined.

Cost model

operationcost
hash compare per probeone 64-bit integer compare, no Python call
__eq__ per probeuser code, unbounded
expected probessmall constant at load factor ≤ 2/3
resize6th insert into an 8-slot table; new size 2× used (3× above 50,000 entries)
worst caseO(n) probes when every key collides

What would change the answer

  • With large keys and expensive __eq__, the cached-hash pre-filter dominates; with small ints, equality is nearly free and the hash function itself is the cost. sys.hash_info gives the parameters: width=64, modulus=2305843009213693951 (2⁶¹−1), algorithm='siphash13' on 3.11+. Int hashing is n % modulus, so hash(2**61 - 1) == 0 and hash(-1) == -2 (−1 is reserved as the error return).
  • If you need stable hashes across processes you're outside hash() entirely: use hashlib, and note you then need collision resistance, not just a bucket function.
  • dict preserves insertion order (3.7+) via a separate entries array; that doesn't change the hash/equality contract, but it's why lookup isn't a scan of that array.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-8

What invariants must a production dictionary key satisfy?

Answer

Short answer: a production dict key must be hashable, its hash must never change while it's in the dict, and __eq__ must be consistent with __hash__, if a == b, then hash(a) == hash(b). Everything else about key choice follows from those two invariants.

Invariant 1: hash stability. hash(k) must return the same value for the object's entire residency in the table. CPython's dict is an open-addressing hash table; the slot index is hash & mask (mask = table size − 1, with perturbation bits on collision), and the table resizes when it's two-thirds full. If the hash changes after insertion, the object sits in a slot its current hash no longer maps to: lookups miss even though the key is "in" the dict. This is why lists and dicts are unhashable by design: their hash would have to change on mutation.

Invariant 2: equality/hash consistency. If a == b, then hash(a) == hash(b). The converse isn't required: unequal objects may collide, which costs probe steps, not correctness. Lookup protocol: hash to find a candidate slot, then verify with == (with an identity fast-path first). Break the consistency and you get the classic bug: an object retrievable by one reference but not by an equal one.

What that rules out:

Candidate keyHashable?Why
int, str, bytes, frozensetYesImmutable, stable hash
tuple of hashablesYesHash combines element hashes
tuple containing a listNohash((1, [2])) → TypeError: unhashable type: 'list'
list, dict, setNoMutable
Custom class instanceYes by defaultDefault __hash__ is id()-based
Class with __eq__ but no __hash__NoPython sets __hash__ = None (documented since Python 3)

The two rows people miss: a tuple is hashable only if every element is (recursively), and defining __eq__ without __hash__ silently makes your class unhashable.

The user-defined trap. A mutable object with an id()-based hash is technically consistent: it works as a key, but by identity, not value. The dangerous case is a value-based __eq__ over mutable state. Trace it:

Python
class Bad:
    def __init__(self, items): self.items = items
    def __eq__(self, other): return self.items == other.items
    def __hash__(self): return 1  # stable, but ignores state

k = Bad([1, 2])
d = {k: "v"}
k.items.append(3)
print(Bad([1, 2]) in d)     # False — no longer == the stored key
print(Bad([1, 2, 3]) in d)  # True — == the stored key, finds "v"
print(d[k])                 # "v" — identity fast-path still works

After the append, the stored key's value has drifted: a fresh object holding the original [1, 2] no longer finds the entry, while one holding [1, 2, 3], data that never existed at insertion time, does. Equal-by-value lookups and the actual stored key have diverged. The fix: hash over exactly the fields __eq__ compares, and make those fields immutable.

What I'd do in production:

  1. Prefer immutable value keys: str, int, NamedTuple, or dataclass(frozen=True). Frozen dataclasses get a field-based __hash__ automatically when eq=True (the default).
  2. Composite keys: frozenset when order doesn't matter, tuple when it does. Note str caches its hash after first computation; tuples recompute on every hash() call, proportional to size: for a hot path doing millions of lookups, a canonical string or int key is measurably cheaper (hashing a short str is tens of nanoseconds; a 10-element tuple pays for ten element hashes per lookup).
  3. If keys come from mutable input, snapshot into an immutable form at insertion: key = tuple(sorted(cfg.items())), not cfg.
  4. Test the contract directly: assert hash(a) == hash(b) for representative equal pairs, and assert hash(k) is unchanged across every code path that touches the key.

If keys genuinely must carry mutable state, they shouldn't be dict keys: key on identity, or move the mutable part into the value.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-5

How do Python dictionaries and sets handle hash collisions, and what triggers table resizing?

Answer

The 90-second answer

dict and set are both open-addressed hash tables: no buckets, no chains. A lookup starts at i = hash & mask; on collision it jumps by a perturbed linear-congruential step:

C
perturb >>= 5;
i = (5 * i + 1 + perturb) & mask;

perturb starts as the full hash and shifts right five bits per round, so keys sharing low bits diverge after the first probe. Table sizes are powers of two, which makes 5*i + 1 (mod 2^n) a full-period LCG: even after perturb reaches zero, the sequence visits every slot once before repeating.

Resizing is load-factor driven, and tombstones count toward it:

  • dict resizes when the index table is two-thirds full (dk_usable <= 0), to the smallest power of two ≥ 3 * ma_used.
  • set resizes when fill * 5 >= mask * 3, 60%, to the smallest power of two ≥ 4 * used (2 * used above 50,000 elements).

A dict therefore doubles (8 → 16 → 32 slots); a set quadruples (8 → 32 → 128). Both are amortized O(1) per insert.

Why this probe sequence

Linear probing (i = (i+1) & mask) merges runs of occupied slots into primary clusters, and every later key pays for them. Separate chaining needs a heap block per bucket and a pointer dereference per probe: a cache miss each time. CPython keeps one flat array and breaks clusters instead: the 5*i + 1 term guarantees full coverage, and perturb mixes in the high hash bits so two keys colliding in the low bits take different paths.

set adds one wrinkle: it first scans up to LINEAR_PROBES (9) consecutive slots before falling back to the perturbed jump, to stay inside a cache line. dict uses the perturbed sequence directly. (C names are from CPython 3.11; the probe sequence and load factors are unchanged in 3.12/3.13.)

Worked trace

Insert 0, 8, 16 into a fresh set. PySet_MINSIZE is 8, so mask = 7, and hash(n) == n for small ints.

keyhashprobe 1probe 2probe 3slot
000 & 7 = 0, free0
888 & 7 = 0, takenperturb = 8>>5 = 0; (5*0+1+0)&7 = 1, free1
161616 & 7 = 0, takenperturb = 16>>5 = 0; (5*0+1+0)&7 = 1, taken(5*1+1+0)&7 = 6, free6

All three hashes collide mod 8, yet they land in slots 0, 1 and 6. The full sequence for perturb = 0 is 0, 1, 6, 7, 4, 5, 2, 3: all eight slots before it repeats. The 9-slot linear run never applies here: it needs i + 9 <= mask, false in an 8-slot table.

Layout

dictset
Tabledk_indices (1/2/4/8-byte ints) + dk_entries (PyDictKeyEntry, 24 B on 64-bit)flat setentry[] (16 B on 64-bit)
Empty / deletedDKIX_EMPTY = -1, DKIX_DUMMY = -2NULL key / dummy sentinel
Orderinsertion order (language guarantee since 3.7)unordered
Resize triggerdk_usable <= 0 (2/3 of index table)fill * 5 >= mask * 3 (60%)
New sizesmallest power of 2 ≥ 3 * ma_usedsmallest power of 2 ≥ 4 * used (2 * used if used > 50000)

The split layout is why dict gets insertion order for free: dk_entries is append-only and dk_indices only stores positions into it.

Failure modes

  • Adversarial collisions. str/bytes hashes are SipHash-1-3 with a per-process random seed, so an attacker can't precompute colliding keys. Ints hash to themselves, so keys 0, 8, 16, 24, … all start at the same slot; the perturbed probe spreads them, but probe counts still climb. Detect it by timing inserts: a healthy dict shows flat per-insert cost, a degenerate one grows linearly with size.
  • Tombstones. Deletes leave DKIX_DUMMY markers that count against the same budget. A dict repeatedly filled and emptied at constant size resizes to the same size to purge them: an O(n) pause that doesn't grow the table. Shows up as periodic latency spikes with flat memory.
  • Resize cost. Rebuilding is O(n) and holds the GIL. A 10-million-entry dict resizing stalls that thread for hundreds of milliseconds; build it once or pre-size rather than growing it in a hot loop.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-12

Walk me through what happens at the table level when you delete a key from a dict or set: why the slot can't just be emptied, what the dummy entry does to later probe sequences, and how accumulated deletions affect resizing and lookup cost?

Answer

Short answer

Assume CPython 3.12/3.13 and an open-addressed table. The language reference doesn't promise that (it guarantees O(1) average lookup, insertion order, and KeyError on a miss) so treat the rest as implementation detail.

A deleted slot becomes a tombstone (DKIX_DUMMY, −2), not an empty slot (DKIX_EMPTY, −1). Empty means "the probe chain ends here, so the key is absent." If del wrote empty, every key that had probed past the deleted slot would become unreachable. Tombstones keep the chain alive, get recycled by later inserts, and count against the table's usable budget, so churn triggers resizes and lengthens unsuccessful probes.

The probe trace

Size 8, mask 7, hash(k) == k for small ints. Insert 1, 9, 17: all start at index 1.

opidx 1idx 4idx 5idx 7
insert 11
insert 919
insert 171179
del d[9]117DUMMY

Probe arithmetic (CPython's perturb probe: i = (i*5 + perturb + 1) & mask; perturb >>= 5):

  • insert 9: index 1 occupied → (1*5+9+1)&7 = 7, empty.
  • insert 17: index 1 occupied → (5+17+1)&7 = 7, occupied → perturb = 17>>5 = 0 → (7*5+0+1)&7 = 4, empty.
  • lookup 17 after the delete: 1 → 7 (DUMMY, keep going) → 4. Found in 3 probes. If index 7 were EMPTY, this lookup would stop at 7 and raise KeyError.
  • lookup 25 (absent): 1 → 7 (DUMMY) → 4 → 5 (EMPTY) → absent. 4 probes instead of 2.
  • insert 33: 1 → 7 (DUMMY, remembered as freeslot) → 5 (EMPTY, absence confirmed) → reuses index 7.

What tombstones cost

Probe length. A miss walks until it hits EMPTY, and tombstones count as occupied. At load α = 2/3 that is roughly 1/(1−α) = 3 probes under uniform hashing, against ~1 for a clean table.

Resize budget. CPython tracks dk_usable, set to USABLE_FRACTION(size) at creation (half the table at the minimum size 8, two-thirds above) and decremented on every new entry. Deletion does not return it. When it hits zero, the next insert calls dictresize, which rehashes into a fresh table and drops every tombstone. The new size comes from the live count (×3 below 50k entries, ×2 above), so a churn loop settles at a table proportional to live keys and resizes every ~2/3·size cycles even though len(d) never moves:

python import sys d = {i: None for i in range(100)} for _ in range(100_000): d[-1] = None del d[-1] print(len(d), sys.getsizeof(d)) # 100; table settles at 512 slots, ~300 resizes

Sets differ. set resizes when fill, used plus dummies, reaches ~60% of the table, so tombstones count directly rather than through a separate budget.

Memory never shrinks on delete. Build 1M keys, delete 999k, and you keep a 2^21-slot table: ~8 MB of int32 indices plus 2^21 × 24-byte entries ≈ 58 MB, for 1000 live keys. sys.getsizeof(d) shows it; dict(d) or d.copy() rebuilds compactly, and d.clear() resets to the minimum table.

Alternatives

SchemeDeleteTrade-off
Tombstone (CPython dict/set)mark DUMMYO(1); chains grow, needs periodic rehash
Backward-shift (linear probing)shift the clusterO(cluster); no tombstones, must preserve probe invariants
Separate chainingunlink nodeO(1), no tombstones; pointer chase per probe
Rehash on deleterebuildO(n) per delete: never

The failure mode worth naming: a long-lived cache dict that peaks at millions of keys and then drains keeps the peak table forever, and every miss pays the longer probe. Detect it by comparing sys.getsizeof to len, or with tracemalloc; fix by rebuilding after a drain threshold. Balanced insert/delete workloads need nothing: the resize trigger already bounds the damage.

Curated: · Written: · Reviewed:

Difficulty: Hard
Q&A-9

Describe Python's dictionary insertion-order contract, including update and reinsertion.

Answer

Short answer

Since Python 3.7 the language guarantees that dict preserves insertion order; CPython 3.6 already did it as an implementation detail. Iterating a dict: for k in d, d.keys(), d.items(), d.values(), reversed(d) (3.8+): yields keys in the order they were first inserted. Two operations have documented behavior:

  • Updating an existing key (d[k] = v where k is present) keeps the key's original position; only the value changes.
  • Deleting a key and reinserting it moves it to the end, because deletion frees the slot and reinsertion appends a new entry.

d.popitem() returns the most recently inserted pair (LIFO) since 3.7. Equality ignores order: {'a':1,'b':2} == {'b':2,'a':1} is True.

Worked trace

Python
d = {'a': 1, 'b': 2, 'c': 3}
d['a'] = 10
print(list(d))        # ['a', 'b', 'c']
del d['b']
d['b'] = 2
print(list(d))        # ['a', 'c', 'b']
d['d'] = 4
print(list(d))        # ['a', 'c', 'b', 'd']

Under CPython's compact dict the entries array evolves like this:

Stepentries array (index: key)iteration order
after literal0:a 1:b 2:ca b c
d['a']=100:a 1:b 2:c (value updated)a b c
del d['b']0:a 1:<dummy> 2:ca c
d['b']=20:a 1:<dummy> 2:c 3:ba c b
d['d']=40:a 1:<dummy> 2:c 3:b 4:da c b d

Iteration walks the dense entries array and skips dummies, which is exactly why order is preserved and why the deleted key reappears at the end.

Why: the compact dict

CPython's dict is two structures:

  1. A sparse index table of small ints, starting at 8 slots (PyDict_MINSIZE) and resized when it is two-thirds full.
  2. A dense entries array of (hash, key, value) triples, appended in insertion order.

Lookup hashes the key, indexes into the sparse table, and follows the pointer to the entry: O(1) average, O(n) worst case under collisions. Iteration is O(n) over the entries array and is cache-friendly because entries are contiguous. Deletion writes a dummy marker instead of compacting, so no other entry moves. On resize the entries are rebuilt in current order, so the contract survives growth.

Tradeoffs and boundaries

AspectConsequence
MemoryThe 3.6 compact layout cut per-dict memory roughly 20–30% versus the pre-3.6 sparse table of full entries
Deletion-heavy workloadsDummies accumulate; a resize reclaims them, so cost is amortized, not free
OrderedDictStill needed for move_to_end(), order-sensitive ==, and popitem(last=False)
Merging{**a, **b} and `a

Failure modes

  • Relying on order on Python < 3.7 (or PyPy pre-3.6 semantics), where it was only an implementation detail.
  • Assuming dict == compares order: it doesn't. Compare list(d.items()) or use OrderedDict.
  • Mutating a dict while iterating raises RuntimeError: dictionary changed size during iteration. Updating an existing key's value is the one safe mutation mid-iteration, because it changes neither size nor position.

What would change the decision

Need reordering or order-aware equality: collections.OrderedDict. Need sorted output: sorted(d.items()). Memory-bound and order irrelevant: a plain dict is still the default. The guarantee costs little but isn't free.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-10

When is a dictionary view useful, and when must it be materialized?

Answer

The 90-second answer

A dict view is a live, read-only window onto the dict. d.keys(), d.values() and d.items() return dict_keys, dict_values and dict_items objects that hold a reference to d and nothing else. Creating one is O(1) and allocates a fixed-size object regardless of dict size, so d.keys() on a ten-million-key dict costs the same as on a three-key dict. That makes views the right tool for one-shot iteration, membership tests, and set algebra over keys or items: anywhere you would otherwise pay for a copy you do not need.

Materialize (list(...), set(...), tuple(...)) as soon as you need a snapshot instead of a window. Three things force it: you are about to mutate the dict while iterating it, because a view raises RuntimeError: dictionary changed size during iteration; you need the keys to outlive the current expression, because a view silently reflects later mutations; or you need sequence behaviour. Indexing, slicing, JSON serialization, repeated passes over a frozen set. The whole decision reduces to "live or frozen?", and getting it wrong costs you either a crash or a silent wrong-data bug.

What the view actually is

dict_keys and dict_items are set-like: keys are unique and hashable, so &, |, -, ^ and <= all work and run as set operations, not scans. dict_values is not set-like, because values may repeat or be unhashable: d1.items() & d2.items() works only when the values are hashable. Views compare by set equality, not order: {"a":1,"b":2}.keys() == {"b":2,"a":1}.keys() is True, while the same comparison on list(...) is False. Views are not hashable, not subscriptable, and not JSON- or pickle-serializable. Since Python 3.8 they support reversed(), and since 3.7 they expose the dict's insertion order.

Python
d = {"a": 1, "b": 2}
ks = d.keys()
d["c"] = 3
print(ks)        # dict_keys(['a', 'b', 'c'])  -- the view moved with the dict
print(len(ks))   # 3
print({"a": 1}.keys() <= d.keys())   # True -- subset test, no copy

When the view is the right tool

Use caseWhy the view wins
d1.keys() & d2.keys()O(min(n, m)), no copy
d2.keys() - d1.keys()O(len(d2)): iterates the left view, probes the right
"x" in d.keys()O(1), same as "x" in d
One pass over current stateZero allocation
Handing live keys to a callbackTracks mutations by design

When you must materialize

  1. Mutating while iterating. The view raises on the next __next__:
Python
d = {i: i for i in range(5)}
for k in d.keys():
    if k % 2 == 0:
        del d[k]
# RuntimeError: dictionary changed size during iteration
# d is now {1: 1, 2: 2, 3: 3, 4: 4} -- the delete happened before the raise

Fix: for k in list(d):. Changing only values of existing keys is safe and does not raise.

  1. Snapshot semantics. A view is not a snapshot:
Python
d = {"a": 1}
snap = d.keys()
d["b"] = 2
print(list(snap))   # ['a', 'b'] -- not what you wanted
  1. Serialization. json.dumps(d.keys()) → TypeError: Object of type dict_keys is not JSON serializable; pickle.dumps(d.keys()) → TypeError: cannot pickle 'dict_keys' object. Use list(d.items()).

  2. Indexing. d.keys()[0] → TypeError: 'dict_keys' object is not subscriptable. Use next(iter(d)) for the first key: O(1) versus O(n) for list(d)[0].

  3. Repeated passes over a stable set. Each pass re-reads the dict; materialize once if the dict may change between passes.

Costs

Viewlist(d)set(d)
CreationO(1), fixed sizeO(n) time, O(n) memoryO(n) time, O(n) memory
Reflects mutationsYesNoNo
Set opskeys/items onlyNoYes
IndexingNoYesNo

On 64-bit CPython 3.12, sys.getsizeof(list(range(1_000_000))) is 8,000,056 bytes (~7.6 MiB); sys.getsizeof(set(range(1_000_000))) is 33,554,648 bytes (~32 MiB), because the set also allocates a hash table. A view of the same dict is a fixed-size object: sys.getsizeof(d.keys()) returns the same value for three keys and ten million.

Failure modes and how to spot them

The loud one is RuntimeError: dictionary changed size during iteration: it fires on the next iteration step after a size change, so the mutation has already happened when you see it. The quiet one is a view used as a snapshot: no exception, just data from the wrong moment, which is why "materialize anything that outlives the expression" is the safe default. A third is TypeError from json.dumps, pickle.dumps, or d.keys()[0]: all three are the same mistake, treating a view as a sequence.

What changes the decision

If the dict is large and you only need membership or one pass, never materialize: the O(n) copy is pure waste. If you hand "the keys" to another module or a callback that may mutate the dict, materializing is a correctness requirement, not an optimization. If you need order-sensitive equality or a sequence contract, the right type is list(d.items()), not a bare view.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-11

Compare subscription, `get`, `setdefault`, and `defaultdict` for missing keys.

Answer

Framing

These four constructs answer different questions about a missing key. d[k] and d.get(k, ...) are read-only; d.setdefault(k, v) and defaultdict are read-or-insert. Assume CPython 3.12; timings below are illustrative timeit figures, order-of-magnitude.

Semantics, with a trace

Python
d = {'a': 1}

d['a']             # 1
d['b']             # KeyError; d unchanged

d.get('b')         # None — absent is now indistinguishable from stored None
d.get('b', 0)      # 0; d still unchanged

d.setdefault('b', []).append(1)   # miss: insert [] under 'b', return it -> {'a': 1, 'b': [1]}
d.setdefault('b', []).append(2)   # hit: a fresh [] is allocated, discarded, existing list gets 2

from collections import defaultdict
dd = defaultdict(list)
dd['x']            # miss: list() called, inserted, returned; len(dd) == 1
dd.get('zzz')      # None — factory NOT called, nothing inserted
'zzz' in dd        # False

The last two lines are the classic trap: defaultdict's factory fires only through __getitem__ (the __missing__ hook), so .get and in bypass it silently.

Comparison

on hiton missinserts on miss?default evaluated every call?factory fires via .get?
d[k]valueraises KeyErrorno——
d.get(k, dv)valuereturns dvnoyes: argument evaluated at the call siteno
d.setdefault(k, dv)existing valuestores and returns dvyesyes: even on hitno
defaultdict(f)[k]valuecalls f(), stores, returnsyesno: only on missno

defaultdict is a dict subclass holding a factory; the same hook is available by subclassing dict and defining __missing__ yourself.

Worked example: grouping 10^6 rows into 10^3 buckets

Python
groups = {}
for row in rows:
    groups.setdefault(row.key, []).append(row)   # 1,000,000 empty lists allocated; 999,000 discarded

groups = defaultdict(list)
for row in rows:
    groups[row.key].append(row)                  # 1,000 lists allocated

setdefault builds its default before knowing whether it is needed: 10^6 allocations vs 10^3. For counting 10^6 words, defaultdict(int) with counts[w] += 1 runs in roughly 0.06 s vs ~0.10 s for counts[w] = counts.get(w, 0) + 1 on one core: the gap is per-iteration default construction, not the lookup itself (~25 ns for a hit via d[k], ~45 ns via .get, the extra being method-call overhead). When misses are rare and absence signals a bug, EAFP wins on the hit path: zero-cost try in 3.11+ makes the non-raising path a bare d[k], and a raised-and-caught KeyError costs a few hundred nanoseconds. Acceptable only when misses are uncommon.

Python
try:
    v = d[key]
except KeyError:
    v = expensive_default()

Failure modes

  • .get with None masks bugs. The None propagates and explodes later (TypeError: 'NoneType' object is not subscriptable), far from the cause. If absence is a contract violation, let d[k] raise.
  • Falsy collisions. d.get(k, '') cannot distinguish absent from stored ''. Sentinel fix: _MISSING = object(); v = d.get(k, _MISSING); if v is _MISSING: ...
  • Eager setdefault defaults. cache.setdefault(key, json.loads(raw)) parses JSON on every call, hit or miss. Expensive defaults need get-then-check or try/except.
  • defaultdict mutates on read. Logging dd[k] for a missing key inserts it; for k in dd: dd[k] over missing keys raises RuntimeError: dictionary changed size during iteration. Read-only access must go through .get/in.
  • Nested defaultdicts create phantom paths. A typo'd dd['a']['b'] inserts both levels. Lambda factories also break pickling and multiprocessing: use module-level factories.
  • Concurrency. Under the GIL, a single dict operation is atomic, so d.setdefault(k, precomputed) is an atomic check-and-set (handy for one-time initialization); get-then-assign is a TOCTOU race. This holds per-operation only, and the free-threaded CPython 3.13+ builds change the reasoning: do not build protocols on it.

Decision rule

  • Absence is a bug (config, required field) → d[k], fail fast; wrap only to enrich the message.
  • Absence is a value, read-only, cheap default → .get; add a sentinel when falsy values are legal.
  • Accumulation or grouping → defaultdict; fall back to setdefault when the object must remain a plain dict (serialization boundary, existing API) or you need the atomic check-and-set.
  • Expensive default with rare misses → try/except KeyError or get-then-check; defaultdict with a cheap factory is still fine because it only pays on miss.

The one-line summary: the choice is really about what a missing key is. An error, a value, or a reason to create something.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-23

What `Counter` behaviors around zero and negative counts matter in production?

Answer

Clarify the question

collections.Counter is a dict subclass, so it inherits normal dict semantics, but it layers on arithmetic and lookup behaviors that treat zero and negative counts specially. The production-relevant behaviors fall into three groups: lookup, storage, and arithmetic.

1. Missing keys return 0, not KeyError

Python
from collections import Counter
c = Counter({"a": 3})
c["missing"]   # 0, no KeyError
c["a"]        # 3

This is the most load-bearing behavior: if c[key] >= threshold is safe without a membership check, so Counter works as a tally without pre-initialization. The tradeoff is silent typo masking: c["recieve"] returns 0, so a misspelled key in a reporting path produces a plausible-looking zero instead of a crash. If absence is itself an error, check key in c or use a plain dict.

Note the asymmetry: reading a missing key returns 0 without inserting it, but an explicit c["missing"] = 0 does insert the key.

2. Zero and negative counts are stored, not normalized

Python
c = Counter(a=1)
c["a"] -= 1
c["b"] -= 1
c                    # Counter(a=0, b=-1)
list(c.elements())   # []  — elements() skips counts <= 0
c.most_common()      # [('a', 0), ('b', -1)] — most_common does NOT filter
len(c)               # 2, not 0

elements() skips non-positive counts, but most_common() returns every entry sorted by count: zeros and negatives included. Meanwhile len(c) and iteration count all stored keys. Production consequence: if you subtract counters repeatedly (say, diffing inventory snapshots), the dict accumulates zero and negative tombstones, so len(c) overcounts active SKUs and memory grows with the number of distinct keys ever touched, not the number currently in play. The documented cleanup is unary plus:

Python
+c   # Counter() — drops a (0) and b (-1)

+c builds a fresh Counter keeping only counts greater than zero: an O(n) copy, so call it at checkpoint boundaries, not in a hot loop.

3. Operators filter non-positives; methods do not

Python
x = Counter(a=2, b=0, c=-1)
y = Counter(a=1, b=1, c=1)

x + y   # Counter(a=3, b=1)      — b: 0+1=1 kept; c: -1+1=0 dropped
x - y   # Counter(a=1)            — b: 0-1=-1 dropped, c: -2 dropped
x & y   # Counter(a=1)            — min, then drop <= 0
x | y   # Counter(a=2, b=1, c=1)  — max, then drop <= 0

x.update(y)     # in-place add, no filtering
x.subtract(y)   # in-place subtract, can go negative, no filtering

The operators (+ - & |) are multiset-style and drop results <= 0; update and subtract are raw tallies. Mixing them up is a real bug source: c1 - c2 can never show a negative delta, so "how much did we oversell?" computed with - silently loses the answer.

Worked trace: recovering a negative delta

Python
stock = Counter(sku=5)
sales = Counter(sku=7)

stock.subtract(sales)   # Counter(sku=-2) — oversold, visible
-stock                  # Counter(sku=2) — unary minus keeps only NEGATIVE counts, negated
+stock                 # Counter()      — unary plus keeps only positive counts

Unary minus is the mirror of unary plus: it keeps only the negative counts and flips their sign. So -stock actually recovers the shortfall directly, Counter(sku=2), which is the idiom to reach for when sign carries information. If you need both sides of the delta, split explicitly:

Python
short = -stock                          # Counter(sku=2)
over  = +stock                          # Counter()

Failure modes at a glance

BehaviorSurpriseMitigation
Missing key → 0Typos read as zeroin check or plain dict when absence is an error
Zero/negative entries persistlen(c) and iteration overcount; memory grows with keys ever touched+c at boundaries
most_common() doesn't filterZeros and negatives appear in "top" listsFilter before display: +c or a comprehension
`+ - &drop<= 0`Negative deltas vanish from -
update/subtract don't filterTombstones accumulate+c at boundaries

The decision rule: use the operators when you genuinely want multiset semantics (non-negative counts only); drop to subtract plus unary minus when sign carries information.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-13

What guarantees should an API avoid making about set iteration?

Answer

What a strong candidate says first

Assume CPython 3.x and that the question is about the contract an API exposes to callers. A set is a hash table with no order contract, so an API should promise exactly three things and nothing more: membership, cardinality, and equality. It should never promise iteration order, insertion order, sorted order, or stability across runs, processes, or Python versions.

Concretely, avoid these claims:

  • "returns the first element" / "returns elements in order"
  • "returns elements in insertion order"
  • "output is deterministic across runs"
  • "iteration order is stable across Python versions or implementations"

The only order guarantee you can honestly make is one you produce yourself: sorted(s).

Why: the mechanism

CPython stores a set in an open-addressed hash table of power-of-two size (minimum 8). An element's slot is hash(key) & mask, with perturbation-based probing on collision. Iteration walks slots 0..mask in index order, so what you see is a function of hashes and table history, not of insertion.

Two consequences:

  • hash(n) == n for small ints, so {3, 1, 2} often iterates as [1, 2, 3]: it looks sorted. That is a coincidence of small-int hashing, not a guarantee.
  • str hashing is randomized per process (PYTHONHASHSEED), so a set of strings can iterate differently in two runs of the same program.

Complexities to quote: x in s, s.add, s.discard are O(1) average, O(n) worst case; sorted(s) is O(n log n) time and O(n) space. CPython resizes when the table is roughly 60% full (fill*5 >= mask*3), another reason order shifts after mutation.

Worked trace

Python
s = {3, 1, 2}      # table size 8, mask 7; hash(n) == n
# 3 -> slot 3, 1 -> slot 1, 2 -> slot 2
list(s)            # scans slots 0..7 -> [1, 2, 3]

The [1, 2, 3] output is the trap: it is slot order, not sorted order. Add a value that hashes elsewhere and the illusion breaks.

For strings the order is not even stable across runs:

Python
s = {"alice", "bob", "carol"}
list(s)        # order varies run to run (PYTHONHASHSEED)
sorted(s)      # ['alice', 'bob', 'carol'] — always

sorted(s) is the only line here whose output you can put in a test.

API phrasing

PhrasingSafe?Why
"returns the elements of the set"Yesno order claim
"returns elements in insertion order"Nofalse for set; only dict keys guarantee this (3.7+)
"returns elements sorted"Nomust call sorted() and say so
"deterministic across runs"Nostr hash randomization breaks it

Tradeoffs and failure modes

  • Promising order costs: sorted() is O(n log n) per call; insertion-ordered behavior needs a dict or an ordered structure with extra bookkeeping. Don't pay for order callers don't use.
  • Failure mode: a test asserting list(my_func()) == [1, 2, 3] passes on the dev box and fails under a different PYTHONHASHSEED or Python version. Fix the contract or the test, not the seed.
  • What changes the decision: if callers need deterministic output (golden-file diffs, reproducible builds), return sorted(...) explicitly and document it. A guarantee you can keep.

Close

"I'd document iteration order as unspecified, return sorted() or a list wherever the result crosses an API boundary or a test assertion, and never index off set iteration, if I catch myself doing next(iter(s)) for anything meaningful, that's a design smell."

Curated: · Written: · Reviewed:

Difficulty: Easy
Q&A-14

Give the cost model for set algebra (union, intersection, difference, symmetric difference, and subset/superset tests) in terms of the sizes of the two operands, and state which mathematical properties (commutativity, associativity, idempotence) hold for each operation.

Answer

Short answer

Let m = len(a) and n = len(b). Every binary set operation is a hash-table walk: one operand is iterated, the other is probed with in. Cost is the size of the iterated operand times the average O(1) probe.

opresultCPython cost (avg)commutativeassociativeidempotent
`ab`unionO(m+n)yesyes
a & bintersectionO(min(m,n))yesyesyes
a - bdifferenceO(m), or O(n) when m > 4nnonono (a-a == ∅)
a ^ bsymmetric differenceO(m+n)yesyesno (a^a == ∅)
a <= bsubsetO(m)non/a (relation)reflexive
a >= bsupersetO(n)non/areflexive

Why the asymmetry

Intersection iterates the smaller operand and probes the larger, so it is O(min(m,n)) rather than O(m+n). Difference has no such symmetry: every element of a is a candidate for the result, so it must iterate a. CPython adds one heuristic, when len(a) > 4 * len(b) it copies a and discards each element of b, same asymptotics, better constant when b is tiny. That is an implementation detail, not a language guarantee.

Union and symmetric difference both allocate a fresh table and insert from both operands, so O(m+n) regardless of overlap. Symmetric difference is a single pass, not (a-b) | (b-a).

Subset tests short-circuit on length: a <= b returns False immediately if len(a) > len(b), otherwise iterates a probing b, so O(m). a >= b is O(n) by the same argument. a.isdisjoint(b) iterates the smaller operand, O(min(m,n)).

Properties

Union and intersection are commutative, associative and idempotent: the lattice join and meet on the power set. Union's identity is ∅, intersection's is the universe.

Difference is neither commutative nor associative: {1,2} - {2,3} == {1} but {2,3} - {1,2} == {3}; ({1,2} - {2}) - {1} == ∅ but {1,2} - ({2} - {1}) == {1,2}. It is not idempotent either, since a - a == ∅. What does hold is (a - b) - b == a - b, which is why applying the same filter twice is safe.

Symmetric difference is commutative and associative, and it is an involution: a ^ a == ∅ and (a ^ b) ^ b == a. That makes the power set an elementary abelian 2-group under ^, with ∅ as identity and every element its own inverse. It is not idempotent in the f(x,x) == x sense.

Subset is a relation, not an operation: reflexive, transitive, antisymmetric (a <= b and b <= a implies a == b), and not commutative.

Failure modes and API traps

  • Worst case is O(m·n), not the average: if every key collides, each probe degrades to a linear scan. Adversarial keys against a hash table are a real DoS vector. CPython randomizes string hashes via PYTHONHASHSEED, which raises the bar but does not save a custom __hash__ that returns a constant.
  • a <= b requires b to be a set; a.issubset(b) accepts any iterable and materializes it first, paying O(len(b)) before the comparison starts.
  • Result type follows the left operand: set | frozenset is a set, frozenset | set is a frozenset. In-place a |= b mutates a and keeps its identity.
  • Sets are unhashable, so {{1}, {2}} is a TypeError; use frozenset when you need a set of sets.

python a, b = {1, 2, 3}, {3, 4} a | b # {1, 2, 3, 4} O(5) a & b # {3} O(2) iterates b, probes a a - b # {1, 2} O(3) iterates a a ^ b # {1, 2, 4} O(5) a <= b # False O(3) length check short-circuits a ^ b == (a - b) | (b - a) # True (a ^ b) ^ b == a # True, involution

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-15

When is `frozenset` a better value model than tuple or set?

Answer

Short answer

Reach for frozenset when the value is a set of things (unordered, unique, membership-tested, combined with &, |, -, ^) and it also has to be immutable and hashable. That combination is what lets it serve as a dict key, an element of another set, a default argument, or a module-level constant you hand out without defensive copies. tuple is the wrong model when order is meaningless and duplicates are noise; set is the wrong model when the value must be hashable or must not change under a caller's feet.

The one-line test: if you'd write x in value or a & b on it, and you'd be annoyed if a caller mutated it, you want frozenset.

Decision rule

Requirementtuplesetfrozenset
Order mattersyesnono
Duplicates meaningfulyesnono
O(1) average membership (x in s)no: O(n)yesyes
Hashable (dict key, set element)yesno: TypeError: unhashable type: 'set'yes
Safe to share without defensive copiesnono: aliasing bugsyes

So frozenset = set semantics + value semantics.

Worked example

Python
PERMS = frozenset({"read", "write"})          # module-level constant

role_map = {PERMS: "editor"}                  # frozenset is hashable
role_map[frozenset({"read", "write"})]        # 'editor' — equal hash, equal value

seen = {frozenset({"read"}), frozenset({"read", "write"})}
len(seen)                                     # 2 — dedupes permission sets

PERMS & {"read"}     # frozenset({'read'})
PERMS - {"write"}    # frozenset({'read'})
PERMS | {"admin"}    # frozenset({'read', 'write', 'admin'})
PERMS ^ {"read"}     # frozenset({'write'})

{PERMS}              # {frozenset({'read', 'write'})}
{ {"read", "write"} }  # TypeError: unhashable type: 'set'

Every binary op returns a frozenset, not a set, so the result stays hashable and you can chain it. The trap worth naming: a - b is difference (elements in a not in b), not symmetric difference. If you meant a ^ b and wrote a - b, you silently drop the elements unique to b and answer a different question: a real bug class in permission and diff logic.

Cost model

Membership is O(1) average for set and frozenset, O(n) for tuple/list. The hash of each element is computed once and cached on the object, so repeated in checks on the same strings are cheap. Memory is where frozenset loses: sys.getsizeof(("read", "write")) is 56 bytes on CPython 3.11/64-bit, while the equivalent frozenset is several hundred bytes, because CPython allocates a power-of-two hash table (minimum 8 slots at 16 bytes each) plus the object header, and keeps the table at most 3/5 full. A 5-element set already holds a 32-slot table. So you pay roughly 5-6x the memory of a tuple to buy O(1) membership and hashability. For a handful of elements you only ever iterate, a tuple is cheaper; the moment in checks or set algebra land on a hot path, frozenset pays for itself.

Tradeoffs and failure modes

  • Mutation trap avoided. Returning a plain set from an API invites callers to mutate shared state; frozenset makes the contract structural rather than documented.
  • No add/discard. To build incrementally, accumulate into a set and freeze at the boundary with frozenset(s).
  • Ordering. Neither preserves insertion order; list(frozenset({"read", "write"})) comes back in hash order, which varies across runs for strings. If output order matters (serialized JSON, a UI list), you need a tuple or list.
  • Equality ignores order and count. frozenset({1, 1, 2}) == frozenset({2, 1}) is True. If duplicates carry meaning, frozenset is the wrong model.
  • Unhashable elements. frozenset({[1]}) raises TypeError: unhashable type: 'list'; you must normalize elements to hashable form first.

What changes the decision

If elements are unhashable (lists, dicts), frozenset is impossible without normalizing them. If the collection is large, read-mostly, and membership is rare, a sorted tuple with bisect.bisect_left can beat set memory. If you need per-element counts, that's collections.Counter, not frozenset.

One-line answer: choose frozenset when the value is a set of things (unordered, unique, membership-tested, combined algebraically) and must also be immutable and hashable; choose tuple for ordered data, plain set for local mutable scratch computation.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-24

How would you model ordered uniqueness without relying on set internals?

Answer

Clarifying the problem

"Ordered uniqueness" means a collection where each element appears at most once and iteration order is deterministic: usually insertion order. In Python I don't need to build the hash table myself: dict is insertion-ordered as a language guarantee since 3.7 (CPython 3.6 had it as an implementation detail), so the real question is what contract I put on top of it and what that costs.

Assumptions I'd state out loud:

  • Elements are hashable.
  • First-occurrence-wins: re-adding an existing element leaves its position unchanged.
  • The API is add, contains, remove/discard, len, and ordered iteration.

Core answer: a thin wrapper over dict

Python
class OrderedSet:
    def __init__(self, items=()):
        self._d = dict.fromkeys(items)   # dedups, preserves first-occurrence order

    def add(self, item):
        self._d.setdefault(item, None)   # no-op if present: order unchanged

    def discard(self, item):
        self._d.pop(item, None)

    def __contains__(self, item):
        return item in self._d

    def __iter__(self):
        return iter(self._d)

    def __len__(self):
        return len(self._d)

    def __repr__(self):
        return f"OrderedSet({list(self._d)!r})"

Trace:

Python
s = OrderedSet([3, 1, 3, 2])
list(s)          # [3, 1, 2]  — duplicate 3 dropped, first position kept
s.add(1)         # no-op; list(s) still [3, 1, 2]
s.add(0); list(s)  # [3, 1, 2, 0] — appended at the end
s.discard(1); list(s)  # [3, 2, 0]

Why not the alternatives

Approachcontainsaddordered?Problem
list + membership checkO(n)O(n)yesin scans; at 10⁴ elements that's 10⁴ comparisons per op
set + parallel list of orderO(1)O(1)yesTwo structures to keep in sync; removal is O(n) from the list
dict keys (above)O(1) avgO(1) avgyesOne extra pointer per entry vs a set
Sorted structure (sortedcontainers.SortedSet)O(log n)O(log n)sort order, not insertionWrong ordering semantics if insertion order is required

The dict version is the standard idiom: it's what dict.fromkeys exists for, and it's the same trick behind the one-line dedup list(dict.fromkeys(items)). One structure, one source of truth for both membership and order.

Costs and failure modes

  • Memory: a CPython dict entry is {hash, key, value}; a set entry is {key, hash}. So the dict costs one extra pointer slot per element, 8 bytes on 64-bit CPython, plus the shared None singleton, allocated once, not per element. The "wasted value" worry is real but small.
  • Deletion: CPython dicts don't shrink on del; they leave dummy entries and only resize on growth. After heavy add/remove churn the table can stay sized for the peak. self._d = self._d.copy() rebuilds a compact table sized to the current length.
  • Unhashable elements: dict.fromkeys raises TypeError immediately. Fall back to an O(n) list scan, or key-extract with dict.fromkeys(map(key_fn, items)) and keep a parallel map from key back to the original object.
  • Last-occurrence-wins: you can't get it by re-assigning. Both d[x] = None and {**d, x: None} leave an existing key in place. You must delete first: d.pop(x, None); d[x] = None moves x to the end.
  • Counts: collections.Counter is a dict subclass and preserves insertion order, but its + - & | operators drop zero and negative counts by design (documented), and c[k] = 0 leaves the key present (affecting len, equality and iteration) so use del c[k] when you mean absence.

Detection: assert len(s) == len(list(s)) after mixed add/remove; assert order survives a list → OrderedSet round trip; for the memory claim, compare sys.getsizeof(s._d) before and after a copy().

What would change the decision

  • O(1) removal plus move-to-end (LRU): collections.OrderedDict.move_to_end.
  • Set algebra with order: implement over the dict. OrderedSet(k for k in a if k in b) for intersection, O(len(a)).
  • Sorted order rather than insertion order: sortedcontainers.SortedSet, O(log n) ops.
  • Thread safety: none of these are safe under concurrent mutation; serialize behind a threading.Lock or hand off to a single writer.

Curated: · Written: · Reviewed:

Difficulty: Medium
Q&A-25

Present a repeatable method for selecting a Python container from workload requirements.

Answer

Choosing a Python container from workload requirements

The 90-second answer. Container choice is an API decision, not a micro-optimisation. I write down the contract the rest of the code will depend on (ordering, uniqueness, keyed access, mutability, hashability) pick the narrowest type that provides exactly that contract, then check the dominant operation's complexity against the real workload size. Callers come to rely on equality semantics, iteration order and aliasing, so swapping the type later is a breaking change rather than a refactor.

Assumptions I'd state before answering: CPython 3.11 on 64-bit, single-threaded, keys hashable, and a known workload size. If the size is unknown, measuring it is step zero.

Step 1: extract the contract from the workload. Five questions, in this order:

  1. Ordering: is insertion order meaningful, is sorted order required, or is any deterministic order fine?
  2. Uniqueness: can duplicates exist, and is deduplication a requirement or a bug?
  3. Access pattern: do I look items up by key, by index, or scan?
  4. Mutability: does the collection change after construction, and must it be hashable (usable as a dict key or set member)?
  5. Dominant operation: append, membership test, keyed lookup, range read, or LIFO/FIFO?

Step 2: map the contract to the narrowest type.

ContractTypeCost (CPython 3.11, 64-bit)
Ordered, mutable, duplicates, index accesslistappend O(1) amortised; x in lst O(n); sys.getsizeof([]) = 56 B, +8 B per slot
Ordered, immutable recordtupleindex O(1); hashable if elements are; sys.getsizeof(()) = 40 B
Key → valuedictget/set/delete O(1) average, O(n) worst; insertion order guaranteed by the language since 3.7
Unique items, membership testssetin O(1) average; iteration order not specified
Unique, immutable, hashablefrozensetsame lookup costs; usable as a dict key
FIFO queuecollections.dequeappend/popleft O(1); list.pop(0) is O(n)
Priority orderheapq over a listheappush/heappop O(log n); iteration is not sorted
Counting / groupingcollections.Counter, collections.defaultdictone pass, O(n) average
Multi-writer concurrencyqueue.Queueplain dict/list are not thread-safe for compound operations

The rule is narrowest-fit: a frozenset instead of a set tells the reader this never mutates and lets it be a dict key; a tuple instead of a list makes the value hashable and signals a fixed record.

Step 3: check the dominant operation against real n. Take "10 M events; dedupe by ID and count occurrences."

Python
from collections import Counter

events = ["a", "b", "a", "c", "b", "a"]
counts = Counter(events)
dupes = [k for k, v in counts.items() if v > 1]

Trace: Counter walks the list once. "a" → 1, "b" → 1, "a" → 2, "c" → 1, "b" → 2, "a" → 3. So counts == Counter({'a': 3, 'b': 2, 'c': 1}), and because Counter is a dict subclass the keys keep first-seen order: a, b, c. The comprehension yields dupes == ['a', 'b'].

At n = 10⁷ the naive if x not in seen: seen.append(x) scans the growing list on every insert, so it does about n²/2 = 5×10¹³ comparisons. At roughly 30 ns per comparison in CPython that is ~1.5×10⁶ s: days, not seconds. Counter does 10⁷ hashes and dict inserts at ~100 ns each, so about a second, plus one pass over the distinct keys.

Memory matters at that size too: a list of 10⁷ distinct ints is an 80 MB pointer array (8 B per slot) plus 28 B per int object, so ~360 MB. array.array('q') or numpy.ndarray(dtype='int64') holds the same values in 80 MB.

Same arithmetic for a queue: draining 10⁶ jobs with list.pop(0) moves the remaining elements each time, ~5×10¹¹ pointer moves; deque.popleft() is O(1), so 10⁶ operations.

Step 4: pin the contract with a test, not just a benchmark.

Python
def test_contract():
    assert list(seen) == ["a", "b", "c"]   # order is part of the contract
    assert hash(frozenset(seen))            # hashability is part of the contract

Concrete failure modes this catches:

  • Equality changes with the type. [1, 2] != [2, 1] but {1, 2} == {2, 1}. If callers compare collections, list → set silently changes results.
  • defaultdict(list) mutates on read. d[missing] inserts an empty list, so a lookup inside a loop grows the dict. Detect by comparing len(d) before and after a read-only pass.
  • Hashability breaks loudly, mutation breaks quietly. tuple → list raises TypeError: unhashable type: 'list' at the point of use. set → frozenset keeps equality ({1, 2} == frozenset({1, 2}) is True) but any .add() raises AttributeError: possibly far from where the object was built.
  • Iteration order. dict order is guaranteed; set order is not. Code that iterates a set and assumes order shows up as flaky tests, not as a crash.

What would change the decision. Key type: hashing long strings or objects with expensive __hash__/__eq__ erodes the O(1) average, and unhashable keys remove the dict/set branch entirely. Memory: past 10⁷ items, array.array, numpy.ndarray or __slots__ classes beat containers of boxed objects. Serialization: if the data crosses a JSON boundary you are constrained to dict/list, and the contract lives at that boundary. Concurrency: a plain dict is fine for one writer; multiple writers need queue.Queue or an explicit lock around the compound operation.

Curated: · Written: · Reviewed:

Difficulty: Medium