Search code examples
pythonobjectvariablesimmutability

In python when we assign a new value to a variable what happens to the old one?


I know that there are other questions like this but they don't answer what happens to the previous value after reassignment, that's why I decided to post a new question. So far I've learned that everything in python is an object, even the variables of type int, float, string, bool are objects, I've read somewhere that when we assign a variable num = 11 then num is not actually storing the value of "11" in it but instead it is a pointer which is pointing at a certain location in memory where "11" is stored, and if we tried to reassign a value to num num = 22 then it will just stop pointing at "11" and start pointing at that new value "22" which will be stored in a different location in the memory, So my question is that what happens to the previous value i.e 11 does that get free'd or deleted??


Solution

  • If there is no longer any reference to an object, it becomes eligible for garbage collection. Usually, it happens immediately.

    It's possible for a reference cycle to exist, one simple case being an object whose reference count is non-zero because it holds the only reference to itself.

    >>> a = []  # A list with a reference count of 1
    >>> a.append(a)  # List now has a reference count of 2: a and a[0]
    >>> del a  # List has a reference count of 1, but no name refers to the list
    

    A separate algorithm is used by a Python implementation to periodically scan all exiting objects to look for such cycles and delete objects that cannot be accessed from the Python code anymore.