Reputation:
So I am getting the following results:
() is ()
returns True
(comparison between two objects)id(()) is id(())
returns False
. (comparison between the representations of object identities)According to the python documentation:
The ‘is‘ operator compares the identity of two objects; the id() function returns an integer representing its identity.
Given case (1), object ()
has the same identity (memory address) as object ()
; but in case (2), the representations of their identities are not identical to each other.
Why is that?
Upvotes: 2
Views: 237
Reputation: 476659
The id(..)
function returns an integer that represents the "identity" of an object so to speak. Although it is true that if two variables x
and y
refer to the same object, x is y
succeed, and the result of id(x)
is equal to id(y)
, that does not mean those integers themeselves are the same object.
You thus should use:
id(()) == id(())
# ^ == not is
In Python, even int
s are objects, and although usually there is a cache such that small integers indeed refer to the same object, the following test will usually fail:
>>> 1234567890 is (1234567891-1)
False
>>> 1234567890 == (1234567891-1)
True
Upvotes: 1