Site Loader

We have heard alot about python being memory efficient and one reason to it is how python allocate memory to declared variables. Python use “tags” to assign values while other common languages including C, C++, Java and C# have variables. Let us discuss the in detail the fundamentals of variables in python.


Most of the common programming languages assign separate memory location to each variable, which can be interpreted as storage box which stores the value assigned to that variable and name of storage box is the name of variable.
In the following code statement variable x is assigned to value 10.
x=10;
This means a value 10 is stored in a memory allocated to variable x or we can say name of memory location is x which stores value 10. Now if we take another variable y and assign value 10 to it, as in line of code below:
y=10;
In this case new memory location with name y is allocated and value 10 is stored inside it. Graphics below represent the exact scenario visually.

In case of traditional languages new memory location is allocated for each variable now if we update y value to 11 as below. Then same memory location will be updated which is already allocated with name y as below:
y=11;

Now if x is assigned to Y then the memory is updated as follow:

On the other hand python consider the values as objects and variables as tags so intead of allocating memory to every variable, memory is allocated to each value. Variable name called tags in python are assigned to their respective values. so if we assign 10 value to x and y in python it is represented in memory as single memory location as figure below describes visually. Now if we compare first figure and figure below we can see how python is using memory efficiently by assigning value to both variables from one memory location with the help of tags.

Similarly, if x is initially assigned to value 10. Now if we assign x with a new value 20 the tag x is re-assigned to new memory location which stores 20 and as value(object) 10 becomes unreferenced object, it is then removed by garbage collector.

Python as a language has its own benefits in terms of efficiency and we can use it better if we know how it works internally. Hope you all love this small article and feel free to leave comments for any improvements. We all are going deeper in technology day by day and we all learn together. Thank You!!

Amrinder Brar

I am a Ph.D. (Artificial Intelligence) research scholar at Punjabi University, Punjab, India. I have 9+ years of experience in teaching and research labs. I have worked with technologies like Asp.Net for web development and most of my experience comes out to be writing scripts in Python, C# and Core Java.

Leave a Reply

Your email address will not be published. Required fields are marked *