Programming · foundation
Mutable vs immutable data
A mutable object's observable state can change while retaining its identity; an immutable value cannot be changed after construction, so an apparent update produces or selects another value. Whether a type is mutable is defined by its language and API.
Why it matters
Immutability reduces aliasing surprises and makes sharing, caching, hashing, and concurrent reasoning safer. Mutation can be efficient and expressive when ownership and update boundaries are clear.
Mental model
How to reason about mutable vs immutable data
With mutation, references before and after an update can point to the same identity with changed state. With immutable data, the old value remains as it was and an operation yields a new value, which may internally share hidden structure.
Analogy
A mutable whiteboard keeps its identity while the writing changes; an immutable printed page is replaced by a new edition while the old page remains unchanged.
Examples
See the boundary, not just the happy path
Worked example · Mutate a list
items = ['a']
items.append('b')Python list.append changes the existing list object. Any alias to that list can observe the added element.
Worked example · Create a new tuple
point = (2, 3)
moved = (point[0] + 1, point[1])The tuple point remains (2, 3); moved is another tuple. Tuple immutability does not imply that every object referenced inside a tuple is itself immutable.
Useful contrast · A fixed binding can reference mutable state
final List<String> names = []; names.add('Ada');In Dart, final prevents rebinding names to another list but does not make the referenced List immutable. Binding mutability and object mutability are separate.
Common mistakes
Misconceptions to remove early
Equating const or final with deep immutability
Some declarations freeze a binding, some construct an immutable value, and some are only compile-time constants. Nested referenced objects may still be mutable unless the language or API guarantees otherwise.
Assuming immutable updates must copy everything
Persistent data structures can share unchanged internal nodes while presenting immutable semantics. The observable contract does not dictate a full physical copy.
Quick check
Can you predict the result?
1. What is the key difference between rebinding a variable and mutating an object?
- • Rebinding changes which value the name denotes; mutation changes the state of the existing object.
- • They are always the same operation.
- • Mutation changes only the variable's spelling.
2. How can an immutable collection update be efficient?
Keep building