Introduction π
In Python, every value is stored as an object. These objects fall under two important categories:
- πΉ Mutable β can be changed after creation
- πΉ Immutable β cannot be changed once created
Understanding mutability is crucial for writing bug-free, efficient Python code β especially when working with functions, loops, and data structures.
Note
π‘ Mutable objects change in place
1. Immutable Types π§
These objects cannot be changed after they're created.
- β int
- β float
- β bool
- β str
- β tuple
- β frozenset
- β bytes
Example: Immutable Integer
immutable_int.py
x = 10
print(id(x))
x += 1
print(id(x)) # Different ID β new objectβ Changing an int creates a new object in memory.
Example: Immutable String
immutable_str.py
s = "hello"
print(id(s))
s += " world"
print(id(s)) # New object createdNote
2. Mutable Types π§
These objects can be modified in place without creating new objects.
- β list
- β dict
- β set
- β bytearray
- β custom class objects
Example: Mutable List
mutable_list.py
a = [1, 2, 3]
print(id(a))
a.append(4)
print(id(a)) # Same ID β modified in placeβ List changed without creating a new object.
Example: Mutable Dictionary
mutable_dict.py
d = {"a": 1}
print(id(d))
d["b"] = 2
print(id(d)) # Same ID3. Key Difference Visualization π
| Type | Changes Allowed? | Memory Allocation | Examples |
|---|---|---|---|
| Immutable | No | Creates new object | int, float, str, tuple |
| Mutable | Yes | Modifies existing object | list, dict, set |
4. Why Does Mutability Matter? π§
- β Helps avoid bugs caused by shared references
- β Affects performance & memory usage
- β Important when passing objects to functions
- β Crucial for understanding deep vs shallow copies
5. Mutability in Function Arguments π₯
Mutable objects can be modified inside a function, affecting the original value.
Mutable Example
func_mutable.py
def modify(lst):
lst.append(100)
a = [1, 2, 3]
modify(a)
print(a) # [1,2,3,100]Immutable Example
func_immutable.py
def modify(x):
x += 10
n = 5
modify(n)
print(n) # Still 5β Integers (immutable) cannot be changed inside the function.
6. Tuple vs List β Common Interview Question π
tuple_vs_list.py
t = (1, 2, 3)
l = [1, 2, 3]
# t[0] = 10 # β Error
l[0] = 10 # β Worksβ Tuples are immutable, lists are mutable.
7. Frozen Set β Immutable Version of Set βοΈ
frozenset_example.py
s = frozenset([1, 2, 3])
# s.add(4) # β Error8. Shared Reference Danger (Mutable) β οΈ
shared_reference.py
a = [1, 2, 3]
b = a # both point to same object
b.append(99)
print(a) # [1,2,3,99]Note
9. Best Practices π‘
- β Be careful when passing mutable objects to functions
- β Use immutable types for keys in dictionaries
- β Prefer immutable types when shared across threads
- β Use copy() or deepcopy() to avoid shared references
10. Cheat Sheet π
| Category | Mutable | Immutable |
|---|---|---|
| Numeric | β | int, float, complex |
| Sequence | list | tuple, str |
| Set Types | set | frozenset |
| Mapping | dict | β |
| Binary | bytearray | bytes |
Conclusion π
You now fully understand Mutable vs Immutable Types in Python! Want the next topic? Try Object Identity, Garbage Collection, Name Binding, or Memory Management. Just tell me! π