Immutable in Python describes data types whose values cannot be changed after they are created. Once assigned, their content remains fixed throughout their lifetime.
Python's immutability principle applies to core types like integers, floats, strings, tuples, and frozensets. When you assign a value to such an object, you're not altering the original-it's replaced with a new object if a change appears to occur.
For example, assigning a new value to a variable referencing an immutable object creates a new object in memory. The old one persists until garbage collected. This behavior prevents unintended side effects in functions and ensures predictable state during execution.
When you create an immutable object, Python stores its value in memory and assigns a reference to it. Any operation that seems to modify the object actually produces a new object with updated content.
Take this string assignment:
name = "Alice"
name = name + " Smith"
The first line creates a string object containing "Alice". The second line doesn't alter that object. Instead, Python concatenates "Alice" and "Smith" into a new string, "Alice Smith", and reassigns the variable name to point to this new object.
This process helps no other part of the program accidentally modifies the original string. If multiple variables reference the same immutable value, changing one doesn't affect others.
Not all Python objects are immutable. The following are immutable by design:
| Type | Examples | Why It Matters |
|---|---|---|
| int | 42, -100 | Cannot be altered; arithmetic returns new objects. |
| float | 3.14, -0.001 | Same rule: operations yield new values. |
| str | "hello", 'world' | String methods return new strings, never modify the original. |
| tuple | (1, 2), ("a", "b") | Cannot insert, remove, or replace elements. |
| frozenset | frozenset({1, 2, 3}) | Set variant with no mutation methods. |
These types are safe to use as dictionary keys or set members because their hash values remain constant. Changing them would break hashing, which relies on consistent identity.
Many developers assume that modifying a list inside a tuple is possible-but it isn't. While the tuple itself is immutable, its contents aren't necessarily. Consider:
data = ([1, 2], "fixed")
data[0].append(3)
print(data)
This prints ([1, 2, 3], 'fixed'). The outer tuple didn't change, but the inner list did. This shows that immutability applies only to the container, not nested mutable objects.
A deeper issue arises with function arguments. Because strings and tuples are immutable, passing them to functions avoids accidental modification. But if you pass a list or dict, changes inside the function affect the original.
Immutability supports safer coding practices. It reduces bugs caused by unexpected state changes, especially in shared data structures.
For instance, using a tuple instead of a list for configuration settings prevents accidental edits:
config = ("debug", True, 5000)
# Later in code:
if config[0] == "debug":
print("Running in debug mode")
Since tuples don't allow modification, no code path can accidentally overwrite the mode setting.
Another benefit appears in hashing. Immutable objects have stable hash values, making them usable as keys in dictionaries. A list cannot be a key because it's mutable-changing it would invalidate the hash. But a tuple can be a key:
cache = {(1, 2): "result"}
print(cache[(1, 2)]) # Output: result
Attempting this with a list raises a TypeError: "unhashable type: 'list'".
I once wrote a caching system using tuples as keys. After switching from lists to tuples, performance improved because the cache could reliably store and retrieve results without re-computing. The system ran faster and had fewer edge cases.
Understanding the contrast between mutable and immutable types helps avoid confusion. Here's a comparison:
| Feature | Immutable (e.g., str, tuple) | Mutable (e.g., list, dict) |
|---|---|---|
| Change after creation? | No | Yes |
| Can be used as dict key? | Yes | No |
| Hash value stability? | Fixed | Changes on modification |
| Memory usage on update? | Creates new object | Modifies existing object |
One non-obvious fact: even though immutable objects can't be changed, their references can be reassigned. That's why the following code works:
text = "hello"
text += " world"
print(text)
Even though the string is immutable, the variable name can be rebound to a new string object. This is different from modifying the original in place.
Another distinction: while strings are immutable, you can simulate editing via slicing and concatenation. But this generates new objects each time, which affects performance in loops.
Use immutable types when data should not change. This includes constants, configuration values, and function parameters that represent fixed states.
When working with collections, prefer tuples over lists unless you need to modify content. This makes your intent clear and reduces risk of bugs.
Finally, remember: immutability isn't about preventing change-it's about controlling it. It enforces discipline in code design and improves maintainability.
Immutable in Python is not a feature of choice-it's a foundational behavior. It shapes how data flows through programs, ensures safety in shared environments, and enables useful patterns like memoization and pure functions.