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.
t = (1, 2, 3); t1 = (1, 2, 3)
. –
Blowtube A Python program is constructed from code blocks. A block is a piece of Python program text that is executed as a unit. The following are blocks: a module, a function body, a class definition
Meanwhile, each command typed interactively is a block.
That's because your first code is inside a code block(a module) and it executed as a unit. For example: In a script as a unit:
x = (1,2)
y = (1,2)
print(x is y) # result is True.
But in interactive shell , when you execute them in two different commands, they are in different code blocks. But in interactive mode:
>>> x = (1,2) # a unit
>>> y = (1,2) # a unit
>>> x is y # result is False
But in interactive mode we can use the fallowing commands:
>>> x,y = (1,2),(1,2) # a unit
>>> x is y # result is True
© 2022 - 2024 — McMap. All rights reserved.
None
which is guaranteed to be a singleton.foo is None
is always safe. docs.python.org/3.8/c-api/none.html#the-none-object – LeatherbackTrue
,False
andEllipsis
. What "no guarantees" really means in this context is that you're never guaranteed to get different object identities for immutable types when the values are the same. – Equidistant