How variables are created in Pyton?

·

2 min read

The other day, I overheard the word, "pointer". I noticed this is something related to creating variables, but not so sure. So, I am going to summarise what it is.

Let's think about the simple case. "a = 10".

In Python, all objects are stored in the heap memory. When you create an object, Python allocates memory from the heap to store the object. In the case of the integer object with the value of 10, Python allocates a fixed amount of memory to store the value of 10.

The object reference a is stored in the stack memory. The stack memory is a special region of memory that is used to keep track of function calls and local variables. When you create a variable, Python creates an entry for it on the stack, which includes the name of the variable and the memory address of the object it points to.

When you assign a new value to a variable, Python creates a new object in the heap with the new value and updates the object reference to point to the new memory location. For example, if you do a = 20, Python creates a new integer object with the value of 20 in the heap and updates the object reference a to point to the new memory location.

Python also provides a mechanism for automatically managing memory allocation and deallocation through a process called garbage collection. When an object is no longer needed, Python automatically frees the memory it occupies in the heap. This process is done using reference counting, where Python keeps track of the number of references to an object and frees the memory when there are no more references to the object.