Mutable vs immutable
A mutable object can change in place: lists, dicts, sets, bytearrays. An immutable object's value is fixed after creation: ints, floats, strings, bytes, tuples, frozensets. Names can still be rebound to a different object.
Detailed Explanation
nums.append(3) mutates the list. n = n + 1 rebinds the name n to a new int; the old int is unchanged. Beginners describe both as "changing n". The distinction is what other names see. If alias = nums, nums.append(3) is visible through alias. If alias = n, n = n + 1 leaves alias on the old int.
Immutability is why some objects can be dict keys. A key's hash must not change while it sits in the table. A list's contents can change, so lists are unhashable. A tuple is hashable when all of its elements are. A tuple that contains a list is not: the tuple's identity is fixed, but its hash would depend on a mutable payload.
Functions receive references. A function that appends to a list argument changes the caller's list. A function that does items = [] rebinds its local name and leaves the caller alone. += on a list mutates; += on a tuple rebinds.
Default arguments are bound once. A mutable default is one object shared across calls. That is the def f(seen=[]) bug. Immutable defaults (None, 0, "", ()) are safe.
Copying is how you break aliasing. A slice nums[:] is a shallow copy: a new list, same element objects. Nested lists still share inner lists. copy.deepcopy clones the graph.
Choose mutability on purpose. A dataclass with frozen=True is a value. A list is a workspace. APIs that return internal lists should return a tuple or a copy if callers must not mutate the invariant.
Code Examples
nums = [1, 2]
alias = nums
nums.append(3)
print(alias) # [1, 2, 3]
n = 1
m = n
n = n + 1
print(m, n) # 1 2print(hash((1, 2))) # works
# hash((1, [2])) # TypeError: unhashable type: 'list'def add(item: str, bucket: list[str] | None = None) -> list[str]:
if bucket is None:
bucket = []
bucket.append(item)
return bucket
print(add("a"), add("b")) # ['a'] ['b']Common Gotchas
Mutable default arguments
one list for every call that omitted the argument.
`+=` on a list vs a tuple
aliases of the list see the change; aliases of the tuple do not.
A tuple of lists is not a safe key
it is unhashable, or if you cheated, the inner list can still change.
`str` methods return new strings
`name.lower()` does not change `name`. Assign the result.