Reputation: 67
We can check if the object type is mutable or not by comparing the new memory location of modified variable with the originally defined variable.
For example - int() is an immutable object in Python. If I try to modify the value of integer type variable, I notice the memory location changes [Code and Output below]. Can someone provide a brief explanation going in the background ?
#initial variable
a = 10
# initial memory location
print(id(a))
#modified variable
a += 1
# new memory location, is it same?
print(id(a))
OUTPUT 93285870446416 93285870446524
Upvotes: 3
Views: 1555
Reputation: 336
Note that contrarily to C, and static-typing languages, Python type-checks only at runtime.
in C you would do:
int a; /* creating a memory space allowing only holding data of integer type */
a = 3; /* storing the value 3, not a character, but an integer, otherwise error is returned at compilation */
in Python, a = 3 first creates an object 3 at a certain memory space, and then links the name a to that object location during assignment. a is then bound to that object by pointing to its memory allocated.
CPython already allocates a memory space for integers in range -5 to 256. If you write now b = 3, b will share the same memory location as b is simply another pointer to the same object 3.
Integers being immutable, if you do a += 1, then a new object 4 is created at a different memory address and then a will points to this new location. b stays bound to the object 3.
Note that if an object is not linked anymore to any names (a, b, etc), then it can be garbage-collected. A counter sys.getrefcount(X) is used to keep track of all the references to a given object "X".
Upvotes: 1
Reputation: 59238
What's going on in the background?
a = 10
int
int
is reserved, giving a memory address, marking that memory as "in use"a += 1
int
int
is reserved, giving a new memory address, because the old one is still in useMaybe another
a += 1
int
int
is reserved, giving a either another new memory address, or reuse the now freed memory address ("old" address)and so on
Upvotes: 7