Saturday, January 12, 2019

Python : Check memory address of a variable

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: 
  1. >>>A=1
  2. >>> id(A)
  3. 1403307696
  4. >>> A=A+4
  5. >>> id(A)
  6. 1403307824
  7. >>>

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:
  1. >>> mylist=[1,2,3,4]
  2. >>> id(mylist)
  3. 841655129352
  4. >>> mylist.append(5)
  5. >>> id(mylist)
  6. 841655129352
  7. >>>

We can clearly see lists in python are mutable as the address of mylist variable remains same.

No comments:

Post a Comment