简体   繁体   中英

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 ie 11 does that get free'd or deleted??

Python keeps track of how many references a particular variable has. If there isn't any reference to a particular value it would be cleaned which is also known as Garbage Collection . So in your case 11 would be removed (garbage collected) by python as soon as it loses the reference.

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.

I had a doubt regarding that answer,after the execution of del a would the list still exist in memory? And after the execution of.append(a) would a copy of a be created to which the element of list references or would the element of list reference to the original list

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM