Reputation: 141
>>p = 5
>>id(p)
140101523888800
>>p = 5.56
>>id(p)
140100617985840
I know on assigning the new value to an existing variable, it points to the new location in the memory at which the new value is stored. But my question is, will the memory location containing the previous value 5
still exists?
If yes, won't it cause memory overflow after a few reassignments?
Upvotes: 4
Views: 2608
Reputation: 47
Basically, you need to understand how the variable is being referenced to the value. When you assign the value, it doesn't that it owns that value. If variable p is referencing 5, it is just indicating that it has 5. Once you re-reference to 5.56, your element 5 will just go away and new element will just be referenced. Make sure to understand how it is referenced.
>>p = 5 #variable p is referencing to value 5
>>id(p)
140101523888800
>>p = 5.56 #same variable p is referencing to the new value 5.56
>>id(p)
140100617985840
Upvotes: -1
Reputation: 310307
You can't really ask a question like this without also specifying a specific python version/implementation. If you're talking about the reference implementation (CPython), you can look at this reference or this one for python3.x.
Specifically:
It is important to understand that the management of the Python heap is performed by the interpreter itself and that the user has no control over it
So it's impossible to answer whether the memory location will still be valid. What we can talk about is whether the object will be collected by the garbage collector. Since CPython relies on reference counting, when you assign a different value to p
, the reference count on the original value decreases by one. If that reference count drops to zero, the object will be collected by the garbage collector. That means that the memory location becomes available for some other object or possibly that python will return that memory back to the operating system. As a user, you have no control over which of these actions the python interpreter will take (or when).
Basically, the python interpreter takes care of all of the details necessary to prevent memory leaks/memory overflow, etc. As a python programmer, you don't need to worry about these details the same way that you would need to worry about them if you were coding in a lower level language like C.
Upvotes: 8