How does python stores variable?

Aman Phogat
3 min readNov 22, 2022

--

The first thing that a programmer learns when he picks up a new programming language is variables, a variable is a value that can change, depending on conditions or on information passed to the program.

Understanding the foundation of any programming language and knowing these intricacies will help in the long run when dealing with files with large codes, to make debugging that is directly proportional to make life easier.

Interestingly enough python has its own way to store variables, In fact, python has different terminology for them and they are called names in python.

So, let’s jump right into the concept so that my readers learn something practical from this blog.

a=5 — — — — — — — -> 1

what exactly do we think might have happened in a programming language, a memory location might have been created for the variable a and the binary code of 5 must have been stored at that particular location.

a=10 — — — — — — — →2

Now, in general, it should have happened that the code above should have changed the binary value stored in the RAM.

Nevertheless, This is not the case with python in python the literals 5 and 10 are stored in the memory as objects and a is treated as a name that is pointing to 5 in equation 1, and then it started pointing to a different object that is 10.

Now, if you think about it carefully you will get to know why python is called a dynamically typed language, that is the data type of a variable is decided at runtime and we don’t have to predefine the data type beforehand like we use to do in C++, java

int a=5

let’s visualize all this with pythontutor one of the best websites to visualize your code.

C++
Python

Here, the python interpreter has just interpreted the first line of the code. Now when we execute the second line of code let’s see what happens.

But, where object 5 went it was automatically taken care of by a python program garbage collector implicitly.

How it helps in achieving dynamic Typing for python, literals are created as objects and they have their data type the programmer just refers to these objects using the name and when these names are assigned to a different object of some other data type it just start pointing to the new object leaving the previous, which is kind of amazing let’s see it side by side in python and C++.

python
C++

See, how C++ throws an error. I hope I was able to make my readers understand what makes python code dynamically typed.

Support me in my writing journey and let’s learn and grow together 🙌.

--

--

Aman Phogat
0 Followers

I am an aspiring Data Scientist, based around New York City, Currently Pursuing a Master's in Computer Science at the Stevens Institute of Technology, New York