What happens is that the interactive Python interpreter compiles every statement separately. Compilation not only produces bytecode, it also produces constants, for any built-in immutable type, including integers. Those constants are stored with the code object as the co_consts
attribute.
Your x = -10
is compiled separately from the y = -10
assignment, and you end up with entirely separate co_consts
structures. Your x, y = [-10, -10]
iterable assignment on the other hand, is a single assignment statement, passed to the compiler all at once, so the compiler can re-use constants.
You can put simple statements (like assignments) on a single line with a semicolon between them, at which point, in Python 2.7, you get the same -10
object again:
>>> x = -10; y = -10
>>> x is y
True
Here we compiled a single statement again, so the compiler can decide it that it only needs a single object to represent the -10
value:
>>> compile('x = -10; y = -10', '', 'single').co_consts
(-10, None)
'single'
is the compilation mode the interactive interpreter uses. The compiled bytecode loads the -10
value from those constants.
You'd get the same thing if you put everything in a function, compiled as a single compound statement:
>>> def foo():
... x = -10
... y = -10
... return x is y
...
>>> foo()
True
>>> foo.__code__.co_consts
(None, -10)
Modules are also compiled in one pass, so globals in a module can share constants.
All this is an implementation detail. You should never, ever count on this.
For example, in Python 3.6, the unary minus operator is handled separately (rather than -10
being seen as a single integer literal), and the -10
value is reached after constant folding during the peephole optimisation. This gets you get two separate -10
values:
>>> import sys
>>> sys.version_info
sys.version_info(major=3, minor=6, micro=3, releaselevel='final', serial=0)
>>> compile('x = -10; y = -10', '', 'single').co_consts
(10, None, -10, -10)
Other Python implementations (PyPy, Jython, IronPython, etc.) are free to handle constants differently again.