Python Tuples, Dict Internals, and Error Handling in a Record Store
Data Structure DesignModel answerLast updated
Answer three fundamentals questions: tuple rebinding and shallow immutability, how a hash table handles insert, lookup, update and delete, and where to raise and catch errors in a record class.
You are asked three connected fundamentals questions in the context of a small Python class that manages records. Answer each in prose, with short code where it helps.
Part 1: Immutability and tuples
- Define an immutable object. How is it different from a name that happens to point at one?
- Suppose
items = (3,)and a second name,backup = items. You then runitems += (1, 2). What areitemsandbackupafterwards, and why? - Compare the costs of indexing a tuple, testing membership with
in, and concatenating two tuples. - If a tuple contains a list, is the tuple deeply immutable? Explain.
Part 2: Hash table behavior
Explain how a hash table supports inserting, finding, updating, and removing an entry in a dictionary. Cover:
- hashing and how a hash maps to a slot,
- collisions and at least one way to resolve them,
- resizing,
- expected versus worst-case cost,
- why keys need a stable hash and a consistent equality.
Do not assume every language or every Python implementation uses the same collision strategy.
Part 3: Errors in a record-management class
The class exposes insert, update, and remove. Explain:
- when each method should raise an error,
- how a caller can catch an expected failure around a call,
- what an exception should and should not do to the stored data.
Give one concrete example of an expected error, and explain why catching every exception silently is harmful.
Assumptions
- Use ordinary Python semantics. Tuple elements are references to objects.
- Constant-time claims for key operations assume hashing and equality comparison have bounded cost.
- Behavior on duplicate inserts and missing keys is an API decision. State the choice you make rather than assuming one.
Clarifying questions worth raising
- Should inserting an existing key overwrite it or be rejected?
- Is a missing record an expected user error or an internal bug?
Hints
Hint 1
Separate the object from the name. Augmented assignment on an immutable type cannot change the object, so think about what the name does instead.
Hint 2
For the hash table, trace one insert end to end: compute the hash, pick a slot, compare on collision, and decide when to grow. Then ask what breaks if a key's hash changes after insertion.
Hint 3
For errors, ask who owns the decision. The class protects its invariants and reports violations; the caller decides whether to retry, show a message, or give up. Think about whether data is half-modified when an exception fires.
Model answer
Easy Try it yourself first — then compare your approach, complexity and edge cases.
Part 1: Immutability and tuples
Immutable object. An immutable object cannot change its own state after creation. A name is just a binding to an object, and rebinding a name is not mutation.
The += example.
items = (3,)
backup = items
items += (1, 2)
# items -> (3, 1, 2)
# backup -> (3,)
Tuples have no in-place add, so items += (1, 2) behaves like items = items + (1, 2). A new tuple (3, 1, 2) is built and items is rebound to it. The original (3,) is untouched, so backup still sees (3,). This is the key contrast with lists, where += mutates in place and every alias sees the change.
Costs.
| Operation | Cost | Why |
|---|---|---|
Index t[i] | O(1) | Contiguous array of references |
Membership x in t | O(n) | Linear scan using equality; stops early on a hit |
Concatenate a + b | O(len(a) + len(b)) | A new tuple is allocated and references are copied |
A consequence: building a tuple by repeated += in a loop is O(n²) overall. Collect into a list and convert once instead.
Shallow immutability. A tuple fixes which objects it references, not the internal state of those objects. t = ([1], 2) followed by t[0].append(9) works and gives ([1, 9], 2). The tuple still holds the same list. Two practical results: such a tuple is not hashable (hashing it hashes the list, which raises TypeError), and it can't be a dict key. Deep immutability needs every nested element to be immutable too.
Part 2: Hash table behavior
Core mechanism. Compute h = hash(key), reduce it to a slot index (for example h mod table_size or a bitmask), and look there.
- Insert: go to the slot. If empty, store the key and value. If occupied by an equal key, this is an update. If occupied by a different key, that is a collision.
- Find: go to the slot and compare. A matching hash is not enough; the table confirms with equality, because different keys can share a hash.
- Update: find, then replace the value.
- Remove: find, then clear the entry. In open addressing a removal must leave a tombstone marker so later probe chains are not cut short; with chaining you simply unlink the node.
Collisions. Two common strategies are separate chaining (each slot holds a small list) and open addressing (probe to another slot by a deterministic sequence). CPython's dict uses open addressing with a perturbed probe sequence, but a good answer says that the strategy is an implementation choice and the interface is the same.
Resizing. As the load factor rises, probe chains lengthen. The table grows (often by a constant factor) and re-inserts all entries. One resize costs O(n), but doubling makes it amortized O(1) per insert.
Complexity.
- Expected: O(1) for insert, find, update, remove, given a well-distributed hash and bounded load factor.
- Worst case: O(n) if many keys collide. Randomized hashing for strings helps against adversarial inputs.
- Hashing the key itself costs time: hashing a string of length k is O(k). So "O(1)" really means O(1) table work plus the cost of hashing and comparing the key.
Stable hash and equality. Two rules must hold: if a == b then hash(a) == hash(b), and a key's hash must not change while it sits in the table. If a mutable key changes, the entry sits in the slot for its old hash and later lookups look elsewhere, so the entry becomes effectively lost. This is why Python allows hashable immutable types (ints, strings, tuples of hashables) as keys and rejects lists.
Part 3: Errors in the record class
Declare the contract first. For example:
insert(key, record)raisesDuplicateKeyErrorif the key exists (no silent overwrite).update(key, record)raisesKeyNotFoundErrorif the key is missing.remove(key)raisesKeyNotFoundErrorif the key is missing.
The alternative choices (upsert, idempotent remove) are also valid; what matters is that the choice is documented and consistent. Treat a missing record as an expected error when it can result from normal user input, and as an internal invariant violation when only a bug could cause it.
Where to raise. The class raises when an operation cannot satisfy its contract. It should validate before mutating, so a failed call leaves the data exactly as it was (the strong exception guarantee):
class DuplicateKeyError(Exception): ...
class KeyNotFoundError(Exception): ...
class Store:
def __init__(self):
self._data = {}
def insert(self, key, rec):
if key in self._data:
raise DuplicateKeyError(key)
self._data[key] = rec
def remove(self, key):
if key not in self._data:
raise KeyNotFoundError(key)
del self._data[key]
Where to catch. The caller decides policy: show a message, retry with different input, or abort.
try:
store.remove(user_id)
except KeyNotFoundError:
print("No such record; nothing to delete.")
Catch the specific exception you expect, around the smallest block possible.
Effect on data. An exception should not leave a half-applied change. If an operation has several steps (say, updating two indexes), either do the checks first or roll back in a try/finally/except before re-raising.
Why not catch everything silently. A bare except: or except Exception: pass hides bugs such as TypeError or an unhashable key, makes failures invisible, and lets callers continue on corrupt assumptions. If you must catch broadly (a top-level request handler), log with a traceback and either re-raise or return a clear failure.
Common mistakes.
- Saying a tuple
+=mutates the original. - Calling a tuple holding a list "fully immutable."
- Claiming dict operations are always O(1) with no mention of hashing cost, resizing, or collisions.
- Mutating data before validating, so a raised error leaves partial state.
- Using one catch-all handler instead of specific, documented exceptions.