Mutability means an object can change in place. Hashability requires a usable, stable hash together with consistent equality behavior.
Distinguish fixed containers from mutable contents and understand why not every value can safely serve as a dictionary key.
An object can remain in a dictionary while a lookup stops finding it. The cause can be a key whose hash changed after insertion. Build on the identity lesson: first distinguish changing an object from rebinding a name, then examine the equality and hash contract that lets dictionaries and sets find their keys.
![Key(["pune"]) filed in slot 6 of a dict's table; after k.fields.append("2026") the same key now hashes to slot 1, which is empty — the lookup says False even though the entry is still sitting in slot 6](/api/assets/python/assets/824d57c44d2da107.png)
+= on a string vs. a list
s += "!" and row += ["b"] look identical. They aren't:
A string can't grow, so += has to build a new one and rebind s. A list can
grow, so += calls its in-place __iadd__ and keeps the same identity. The gap
only shows when someone else is still holding the original:
t = (1, 2)
u = t
t += (3,)
print(u)Preparing this topic’s interactive investigation…
A tuple that still isn't fully frozen
A tuple locks which objects it holds, not whether those objects can change:
t = ([1, 2], "x")
try:
t[0] += [3]
except TypeError:
pass
print(t[0])A tuple's immutability is shallow: it guarantees its own slots never point somewhere else, and says nothing about what those slots contain.
A dict key that goes missing
A dict uses a hash to narrow its search and equality to confirm a matching key, accounting for collisions. A key's hash must stay stable, and equal keys must hash equally. Attributes unrelated to equality and hashing may still change. The slot numbers below are only for illustration, since the real ones depend on the table's size:
A dict files each key in the slot its hash picks. If a key's hash changes after it is filed, later lookups may search along a different path and fail.
The tuple ("pune", 2026) hashes to a number that picks slot 3, so the key is filed there. 8 cells. At index 3.
The entry never left. Step through the same class and watch found:
After the append, found may become False although still_there is True.
The lookup uses a changed hash; an accidental successful lookup does not restore
the contract. The rebuild near the end hashes each key again, which can also
merge keys that have become equal. It repairs this table state but cannot prevent
the next mutation. Keep the values used by equality and hashing stable.
Freeze the fields into a tuple, and refuse to let them be reassigned:
The built-in mutable collections used here refuse hashing:
hash([1, 2]), hash({"a": 1}) and hash((1, [2])) all raise TypeError — even
a tuple is only hashable if everything inside it is.
Equality and hashing are a two-part contract
The identity lesson asked whether two names reach one object. A dictionary asks a different question: whether a candidate key is equal to a stored key. Hashing narrows the candidates; equality decides the match. Equal keys must have equal hashes, but unequal keys may share a hash. A collision is normal, not lost data.
The result is 2 closed: equal hashes did not merge different tickets. Keep
number unchanged while these keys are stored. A production value key would
normally hash an immutable identifier instead of deliberately creating collisions.
Mutability alone does not decide hashability. An ordinary instance using identity equality can change its attributes and remain a valid identity key. Trouble starts when attributes used by equality or hashing can change. Likewise, a tuple containing a list is immutable as a container but unhashable.
For the deduplication task, state the equality policy first. This course uses
Python equality, so True, 1, and 1.0 compare equal. A typed data format may
need to distinguish them. Transfer the rule to a cache: if two requests have the
same user ID but different locale, should they share an answer? The key must
include every input that changes the intended result.
Freeze a row before using it as a key
Quarry's rows are lists and dicts, straight from JSON — never hashable as they are. To dedupe them, freeze each row into an equal-meaning immutable value, recursively:
frozenset for a dict's items ignores order, the same way dict equality does.
One trap worth knowing: True == 1 and hash(True) == hash(1), so {1, True}
has a single element. If a column might hold either, freeze (type(v).__name__, v) instead of the bare value.
Quick practice
results = []
for value in ([1, 2], (1, 2), {"a": 1}):
try:
hash(value)
results.append("hashable")
except TypeError:
results.append("unhashable")
print(" ".join(results))Each call should start its own log. Run it, notice a and b are the same list, then fix the default.
🎯 Your turn
Write dedupe_rows(rows) for the inspector. rows is a list of JSON values —
lists, dicts, strings or numbers, nested to any depth. Return the rows with
duplicates removed, keeping the first copy and the original order. Two rows
are duplicates if they're equal, including dicts whose keys appear in a different
order.
dedupe_rows([[1, 2], [1, 2], [2, 1]])→[[1, 2], [2, 1]]dedupe_rows([{"id": 1, "tags": ["a"]}, {"tags": ["a"], "id": 1}])→[{"id": 1, "tags": ["a"]}]
Hint: freeze each row (lists → tuples, dicts → frozensets of (key, frozen value) pairs, recursively), and use a set of frozen forms to check "seen before"
in one hash lookup instead of comparing against every row so far.
Press ▶ Run, then ✓ Check. ✅
Practice — level up
0/6 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write hashable_flags(values) returning a list with one boolean per value: True if it can be a dict key, False if not. Ask Python rather than checking types: try hash(value) and catch the TypeError.
start_log(first, log=[]) is meant to start a new log unless an existing one is passed in. Fix it, and write fresh_logs(firsts), which returns [start_log(f) for f in firsts]. With the shared default, every entry is the same growing list.
Write group_counts(rows, fields). Each row is a dict. Group the rows by the values of the named fields. Those values can be lists, so freeze them to build the key. Return [[values, count], ...] in first-seen order, where values is the list of the ORIGINAL field values from the first row in the group.
Write a class Coord(x, y) that is safe to use as a key. Two Coords with the same x and y must be equal and hash the same, and once built, any attribute assignment must raise AttributeError. Then coord_report(points) (given) builds one per [x, y] point, collects them in a set, tries to move the first one, and returns what happened.
BadKey (given) hashes a list it still lets you change. Write stranded(keys, edits). Build a dict mapping BadKey(list(items)) to its index, for each list in keys. Apply each edit [i, value] by appending value to key i's list. Return {"stranded": [...], "entries_after_rehash": n}, where stranded lists, in order, the indices whose lookup table.get(key) no longer returns their own index, and n is the size of the dict after rebuilding it from its items.
A teammate wants Quarry's Row objects in a set, so they add __hash__ returning hash(tuple(self.fields)), while other stages keep editing row.fields in place. Explain what will go wrong and when, and propose a design that keeps both the set and the editing.