Memory Block in Python!

Article #010

In today's article, we will have a short discussion on the memory blocks in Python.

Say there is a variable 'var' having the value '10'. Now in Python, a specific memory location is allocated to the value and not the variable. This means that if different variables have the same value then Python will refer to the same memory block for all these different variables.

We can even verify the above claim by simply using a function called id(). Let's understand this with the help of below codes.

Say we have three variables 'a', b' & 'c'
a = 12
b = 20
c = 12
id(a) will yield a memory location say 12345678
id(b) will yield a memory location say 12344444
id(c) will yield a memory location say 12345678

We can see that the memory location for variables 'a' and 'c' is the same while that of 'b' is different. This is due to the fact that 'a' and 'c' variables have the same value. Let's consider another example.

Say we have two variables 'a' & 'b'
a = 12
b = 12.0

type(a) will yield int
type(b) will yield float

id(a) will yield a memory location say 12345678
id(b) will yield a memory location say 12344444

In the above example, even though the numerical value for both variables is same. But, their data type is different and this is the reason for them having different memory locations. One memory location is saving integer value 12 while the other memory location is saving the float value 12.0

Hope the above discussion is helpful in getting some idea about how memory allocation works in Python.