I just watched this informative video on memory management in Python. In it, the presenter used the following code example (at about the 4:15 mark):
x = 300
y = 300
In this case, we have two names (x
and y
), each pointing at a value of 300. How did Python, when executing the y = 300
line, know that it didn't need to allocate memory but rather increase the reference count, since memory for that value had already been allocated (through x
)? Is the interpreter comparing values on each instantiation? If so, how does it keep track of the values it already knows about (I would assume it would do so using a dict
)?
Suppose I introduced a new variable:
z = 100 + 200
Would z
end up simply increasing the reference count to 300 once more?
When I try the following in my REPL (Python 3.6, Windows 7 x64), I get differing memory locations, which further confuses me (though, to be fair, she says not to try this in a REPL):
>>> x = 300
>>> y = 300
>>> print(id(x))
31191600
>>> print(id(y))
31191648