An immutable object is one whose value cannot be altered once it has been created. In Python, the core immutable types are int, float, bool, str, tuple, frozenset, and bytes. When you perform an operation that appears to modify an immutable object — such as string concatenation or integer addition — Python actually creates a new object and rebinds the name to it. The original object remains unchanged (and is eventually garbage-collected if nothing else references it).
Immutability has several practical consequences. Immutable objects are hashable by default, which means they can be used as dictionary keys and set elements. They are inherently thread-safe because no thread can change their state. They also support certain optimisations: CPython caches small integers and interns short strings, reusing the same object instead of creating duplicates.
A subtle point is that immutability applies to the object itself, not to objects it references. A tuple is immutable — you cannot add, remove, or replace its elements — but if one of its elements is a mutable object like a list, that list can still be modified. This is why a tuple containing a list is not hashable: the hash could change if the inner list changes.
Discussed in:
- Chapter 3: Variables and Data Types — Names, Not Boxes