Python has a built in function to check memory location of a variable.
The variable "id" can be used for this purpose.
Using this special built in function you will get amazing insight on how assignment and other operations works in python.
eg:
As you can see in python the memory address of a variable changes when we add integers. As integer variables are immutable similar to string. In this case when we add integer python allocated a new memory to variable and discarded older location.
On the other hand let's see what happens to a list:
We can clearly see lists in python are mutable as the address of mylist variable remains same.
The variable "id" can be used for this purpose.
Using this special built in function you will get amazing insight on how assignment and other operations works in python.
eg:
- >>>A=1
- >>> id(A)
- 1403307696
- >>> A=A+4
- >>> id(A)
- 1403307824
- >>>
As you can see in python the memory address of a variable changes when we add integers. As integer variables are immutable similar to string. In this case when we add integer python allocated a new memory to variable and discarded older location.
On the other hand let's see what happens to a list:
- >>> mylist=[1,2,3,4]
- >>> id(mylist)
- 841655129352
- >>> mylist.append(5)
- >>> id(mylist)
- 841655129352
- >>>
We can clearly see lists in python are mutable as the address of mylist variable remains same.
No comments:
Post a Comment