Memory address or assigning the value

a=4
a=“coding blocks”
print(a)
it will print “coding blocks”
this means that pythons has a memory block of 4 also?
#waste of memory?

There is a garbage collector that does the background job for u. Python is all based on pointers. Each of the variables actually points to a memory block which has some content. And the number of variables that are pointing to a memory block is called its reference count. When the reference count of a memory block gets 0. The gc collects that memory back. U can see the reference count of a memory block Using sys.getrefcount(obj)
So when u say a= 4
It looks in the table for the 4 whether created previously, If there exist one. a now points to that memory block.
If there isn’t any, python allocates the memory and puts 4 there.

In later releases, after the first 2 3 versions. Python actually makes certain memory blocks as soon as the interpreter starts for Frequently used values Like 1, -1 etc.

So when you say a= 4, then a = “some string”, the ref count of 4 gets down to 0 and now it’s collected. Basically, when we change the value of a variable, the value stays there only, the variable starts pointing to some new value u have given. But 4 is now not taking space bcoz of this reference count becomes 0 and collected by GC.
Also, try using the “is” operator
It actually returns whether 2 variable points to the same value or not.
You can also refer to this blog for more info : https://medium.com/@tyastropheus/tricky-python-i-memory-management-for-mutable-immutable-objects-21507d1e5b95

I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.

On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.