Reputation: 4570
I know the is
operator compares the id of the two, not the value
However when you evaluate id(1) and id(1), the object (which is an int) is equal to one another.
So why is it returning false?
id(1) # 27533656
id(1) is id(1) # False
type(id(1)) # int
so then, technically, deduce it to
id(1) is id(1)
27533656 is 27533656 # has to be True!
Upvotes: 3
Views: 847
Reputation: 10489
You're slightly misinterpreting what the is
syntax does.
What you are doing with that bit of code is roughly:
id(id(1)) == id(id(1))
Because the value returned by the id
function is not static and not guaranteed to be the same identity, they will most likely be different identities.
As proof, when I put those into a print statement I get:
print id(id(1)) # 4327028
print id(id(1)) # 4326968
Which are obviously not the same.
If you were to change the code to:
if 1 is 1: # basically in this case id(1) == id(1)
print "success"
You would find that the values are indeed the same id.
As noted in the comments. The x is x
and id(x) == id(x)
methods of determining equivalence are not always the same for all literal types.
In the specific case of this question they may be treated as equal.
Upvotes: 5
Reputation: 309861
is
checks for object identity whereas ==
checks object equality. The difference can be subtle, but is most easy to see when dealing with mutable objects like lists:
x = [1, 2, 3]
y = x[:] # copy, not the same list
x is y # False
x == y # True
If I add something to x
, y
won't see it:
x.append(4)
x == y # now False since they have diverged.
But, if I alias x
and append to it, the alias will also see the changes:
z = x # alias `z` to `x`
x.append(5)
x == z # True
And the reason for this is because z
is x
.
z is x # True
In this case, the id
of 1
is consistent because CPython1 caches small integers for efficiency (so the object literal 1
is always the same object -- and therefore the same Id). However, the return value of id
can actually be a different instances of int
that have equivalent values.
1This is a well known implementation detail for CPython. Other implementations (and future versions) are free behave differently so do not rely on this behaviour.
Upvotes: 6