I'm running:
Python 2.7.8 (default, Oct 6 2017, 09:25:50)
GCC 4.1.2 20070626 (Red Hat 4.1.2-14) on Linux 2
As per the documentation:
The operators
is
andis not
test for object identity:x is y
isTrue
if and only ifx
andy
are the same object.
To get an object's identity, we can use the id
function.
If we open up a new REPL we can see that 300
and -6
have the same identity (on CPython, this means that both refer to the same memory address):
>>> id(300)
94766593705400
>>> id(-6)
94766593705400
Note that the actual values may differ from execution to execution, but they are always equal.
However, doing 300 is -6
yields False
:
>>> 300 is -6
False
I have a couple of questions:
300
and -6
share the same identity?300 is -6
yielding False
?After id(300)
is executed, no more references to 300
exist, so the id is freed. When you execute id(6)
, it gets that same chunk of memory and stores 6 instead. When you do -300 is 6
, -300
and 6
are both referenced at the same time, so they won't have the same address anymore.
If you keep references to both -300
and 6
, this happens:
>>> a, b = -300, 6
>>> id(a)
some number
>>> id(b)
some different number; 6 is still in the other memory address.
Note: In CPython, numbers from -5 to 256 (I think) are cached, and will always have the same address, so this will not happen.
This is documented behavior of the id()
function:
Return the “identity” of an object. This is an integer (or long integer) which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same
id()
value.
The lifetime of an integer object in the sample code is just the function call (e.g. id(300)
) as no other references to it exist.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With