Python – Immutable Data Structures
In Python programming, data structures can be classified into two types:
- Mutable (can be changed)
- Immutable (cannot be changed)
Immutable data structures are those whose values cannot be modified after creation.
Once created, they remain fixed in memory.
Examples include:
- Strings
- Tuples
- Frozensets
These are widely used for data safety, performance optimization, and hashable objects.
What is an Immutable Data Structure?
An immutable data structure is:
A data type whose content cannot be changed after it is created.
If you try to modify it, Python creates a new object instead of changing the original.
Why Use Immutable Data Structures?
Immutable objects provide:
- Data safety
- Thread safety
- Predictable behavior
- Better performance in some cases
- Hashable objects for dictionaries and sets
1. Immutable Strings
Strings in Python are immutable.
Example:
text = "Hello"
text[0] = "h"
Output:
TypeError: 'str' object does not support item assignment
Correct way:
text = "Hello"
text = "h" + text[1:]
print(text)
2. Immutable Tuples
Tuples are fixed collections.
Example:
my_tuple = (1, 2, 3)
my_tuple[0] = 10
Output:
TypeError: 'tuple' object does not support item assignment
Why tuples are useful:
- Faster than lists
- Memory efficient
- Can be used as dictionary keys
3. Frozenset (Immutable Set)
A frozenset is an immutable version of a set.
Example:
fs = frozenset([1, 2, 3, 4])
print(fs)
Output:
frozenset({1, 2, 3, 4})
Cannot modify:
fs.add(5)
Output:
AttributeError: 'frozenset' object has no attribute 'add'
Mutable vs Immutable
| Feature | Mutable | Immutable |
|---|---|---|
| Can change | Yes | No |
| Memory reuse | Yes | No |
| Thread safety | Low | High |
| Examples | list, dict | tuple, str, frozenset |
How Immutability Works Internally
When you modify an immutable object:
text = "Python"
text = text + " Rocks"
Python does NOT change the original string.
Instead:
- Creates a new string object
- Assigns new reference
Advantages of Immutable Data Structures
1. Thread Safety
Multiple threads can safely read data.
2. Hashable Objects
Can be used as dictionary keys:
my_dict = {("a", "b"): 100}
print(my_dict)
3. Performance Benefits
Python can optimize memory usage internally.
4. Predictable Behavior
No accidental changes in data.
Real-World Use Cases
1. Configuration Data
CONFIG = ("DEBUG", False, "v1.0")
2. Database Keys
Tuples used as composite keys:
users = {
("John", "USA"): 25
}
3. Security-Sensitive Data
Immutable objects prevent accidental modification.
When to Use Immutable Structures
Use them when:
- Data should not change
- You need dictionary keys
- You want safer multi-threading
- You want predictable data flow
When NOT to Use
Avoid immutability when:
- Data changes frequently
- You need dynamic updates
- Performance of updates is critical
Common Mistakes
1. Thinking tuples are always safe
Tuples can still contain mutable objects:
t = ([1, 2], 3)
t[0].append(4)
print(t)
✔ Tuple is immutable, but inner list is mutable
2. Confusing reassignment with mutation
x = "Hello"
x = "Hi"
✔ This is reassignment, not modification
Summary
Immutable data structures in Python ensure that once data is created, it cannot be changed.
They improve:
- Safety
- Performance
- Predictability
They are widely used in modern applications built with Python.
Conclusion
Understanding immutable data structures is essential for writing clean and reliable code in Python.
They help prevent bugs, improve performance, and ensure safer data handling in complex applications.


0 Comments