Python Internals - Mutable vs Immutable Objects
Understanding Python internals is crucial for writing bug-free code and is a favorite topic in technical interviews. On Day 1, we focus on how Python handles objects in memory, mutability, function arguments, and object identity.
Let’s break it down step by step.
1. Mutable vs Immutable Objects in Python
In Python, everything is an object, and each object is either mutable or immutable.
1a. Immutable Objects
Immutable objects cannot be changed after creation.
Examples:
intfloatstrtuple andfrozenset
Input
Output - 10
- a = 10
- b = a
- b += 1
- print(a)
Output - 10
π§ This is because
When
int is immutable.When
b += 1 is executed, Python creates a new object for b.a still points to the original value 10.1b. Mutable Objects
Mutable objects can be modified in place.
Examples:
listdictset andMost Custom Objects
Input
- a = [1, 2, 3]
- b = a
- b.append(4)
- print(a)
- Output
π§ This is because lists are mutable.
Both a and b reference the same object in memory, so modifying one affects the other.
Comments
Post a Comment