Mutability and Hashability in Python

Mutability describes whether an object's state can be modified in place, whereas hashability determines whether it can serve as a dict key or set member.

One-Line Definition

Mutability describes whether an object's contents can be altered in place after creation; hashability describes whether an object has a stable hash value suitable for dictionary keys and set members. The two concepts are closely related but not identical—nested containers and custom equality rules both matter.

Why It Matters

  • Determines what can be used as a dict key or set element: Only hashable objects (which are almost always immutable by value) are allowed.
  • Governs whether sharing references is safe: Objects whose reachable state never mutates can be passed across functions and threads without defensive copying; shared mutable objects require discipline.
  • Explains one of Python's most notorious gotchas—mutable default arguments.

Usage Boundaries

User-defined mutable class instances are hashable by object identity by default, whereas an immutable tuple becomes unhashable if any element inside it is unhashable. frozendict became a built-in type in Python 3.15 and does not recursively freeze mutable values stored inside it.

How It Works / Diagram

Type Mutable? Hashable? Notes
int, float, bool, str, bytes No Yes "Modifying" always allocates a new object
tuple No Only if every element is hashable A tuple containing a list is unhashable
frozenset No Yes Immutable set
frozendict (new in 3.15) No Only if all keys and values are hashable Added in PEP 814
list, dict, set, bytearray Yes No
Custom class instance Yes by default Hashable by identity by default @dataclass(frozen=True) blocks attribute reassignment but does not recursively freeze mutable field contents

Python 3.15 (released 2026-10-09) introduced the built-in frozendict type: it is not a subclass of dict, preserves insertion order while comparing order-independently, and is hashable whenever all of its keys and values are hashable: https://docs.python.org/3.15/whatsnew/3.15.html#pep-814-add-frozendict-built-in-type

How the mutable default argument trap works under the hood:

Figure 1

The official Python tutorial explicitly warns: "The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes": https://docs.python.org/3/tutorial/controlflow.html#default-argument-values

Runnable Example

# File: examples/19_mutability.py
# Mutable vs. immutable objects, plus the classic mutable default argument trap
import sys
print("Python", sys.version.split()[0])

s = "abc"
try:
    s[0] = "z"
except TypeError as e:
    print("str is immutable:", e)

t = (1, [2, 3])           # The tuple container is immutable, but the inner list is mutable
t[1].append(4)
print("Inner list inside tuple mutated:", t)
try:
    hash(t)
except TypeError as e:
    print("Therefore this tuple is unhashable:", e)

# Classic trap: default arguments are evaluated once at function definition time
def bad(item, bucket=[]):
    bucket.append(item); return bucket
def good(item, bucket=None):
    bucket = [] if bucket is None else bucket
    bucket.append(item); return bucket
print("bad :", bad(1), bad(2))
print("good:", good(1), good(2))

# Benefit of immutability: usable as a dictionary key and safe to share
cache = {(3, 4): 5.0}
print("Tuple as dict key:", cache[(3, 4)])

# Python 3.15 built-in frozendict (PEP 814): immutable, hashable mapping
if sys.version_info >= (3, 15):
    fd = frozendict(model="deepseek", temperature=0.2)
    print("frozendict:", fd, "| hashable:", hash(fd) == hash(frozendict(temperature=0.2, model="deepseek")))
    try:
        fd["model"] = "x"
    except TypeError as e:
        print("frozendict cannot be mutated:", e)

Recorded output (Python 3.15.0):

Python 3.15.0
str is immutable: 'str' object does not support item assignment
Inner list inside tuple mutated: (1, [2, 3, 4])
Therefore this tuple is unhashable: unhashable type: 'list'
bad : [1, 2] [1, 2]
good: [1] [2]
Tuple as dict key: 5.0
frozendict: frozendict({'model': 'deepseek', 'temperature': 0.2}) | hashable: True
frozendict cannot be mutated: 'frozendict' object does not support item assignment

Notice bad : [1, 2] [1, 2]: both calls mutate and return the exact same underlying list object, so by the time print evaluates both return values, both references show [1, 2].

Common Misconceptions

  • "A tuple is immutable, so nothing inside a tuple can ever change": A tuple only guarantees that the tuple slots keep pointing to the same object identities; if one slot holds a list, that list can still be mutated in place.
  • Thinking s += "x" mutates a string in place: Strings are immutable, so concatenation allocates a new string and rebinds the variable name. Use "".join(...) when accumulating many fragments in a loop.
  • Using a mutable literal as a function default: Always default to None and create a fresh container inside the function body. Ruff's B006 lint rule flags this automatically: https://docs.astral.sh/ruff/rules/mutable-argument-default/
  • Assuming @dataclass(frozen=True) performs a deep freeze: Just like a tuple, if a frozen dataclass has a list attribute, elements can still be appended to that list.

Connection to AI Development

  • Memoization requires hashable cache keys: Decorators like functools.cache require every argument to be hashable. Wrapping generation parameters in a frozendict or tuple lets you cache LLM responses by configuration cleanly.
  • Pandas 3.0 Copy-on-Write: Shifts DataFrame slicing semantics away from error-prone in-place mutation rules so derived views behave like independent copies, preventing accidental mutation of upstream training tables (see k1.lib.pandas).
  • Multi-threading and free-threaded Python: When running without the GIL, concurrent mutation of shared dictionaries or lists causes data races directly; immutable data structures eliminate shared-mutation hazards across worker threads (see k1.py.threading).

Further Reading

Comprehension Check

Why does Python raise a TypeError if you try to use a tuple containing a list as a dictionary key?

Reference answer: A tuple's hash value is computed from the hashes of all of its elements; because a mutable list is unhashable, the enclosing tuple cannot be hashed either.

Verification & Reproduction

Verified on: 2026-10-14. Example status: Passed (verified on Python < 3.15 with the frozendict guard branch skipped, and recorded on Python 3.15.0). Run log: 19_mutability.py.

Companion Code & Verification Materials

Back to Foundations Back to Learn →Back to top ↑
On this page
Tutorial diagram100%
Tutorial diagram