t = (1,2,3)
t1 = (1,2,3)
print(id(t))
print(id(t1))
The above lines of code gives the same addresses in script mode in Python, but in interactive mode it outputs different addresses. Can anyone explain the reason for this?
t = (1,2,3)
t1 = (1,2,3)
print(id(t))
print(id(t1))
The above lines of code gives the same addresses in script mode in Python, but in interactive mode it outputs different addresses. Can anyone explain the reason for this?
When the script is being compiled, the compiler can search for all the equivalent tuples and generate code to use the same reference for all of them.
But in interactive mode, it would need to keep a cache of all tuples so it could search for a previous equivalent tuple and return a reference to it, rather than creating a new tuple each time. The interactive interpreter doesn't do this.
If you assign both variables on the same line, you actually get the same tuple.
t = (1, 2, 3); t1 = (1, 2, 3)
This is presumably because it's running the compiler for each input, so it can do the full analysis and optimization.