Reputation: 1
x1 = 51
x2 = 51
id(x1)
id(x2)
id(x1) is id(x2)
As I know, Python creates an object and references to it. So id(x1)
and id(x2)
are the same.
But why does the line id(x1) is id(x2)
result in False
?
Upvotes: 0
Views: 65
Reputation: 51162
This question revolves around issues covered in these other questions:
The first thing you need to know is that the same value can be represented by multiple different objects. For example, you can have the number 5000 which is an int
object, and another copy of the number 5000 as a different object int
object at a different location in memory.
The second thing you need to know is that is
tests if two objects are the same object at the same location in memory, not just that their values are equal (that's what ==
tests).
The third thing you need to know is that in current versions of CPython, the objects for small numbers like 51 are cached, so you don't get multiple copies of them; you always get the same object from the cache, even if 51 appears more than once in your program (except in obscure cases).
Given all of that, the behaviour you observe follows:
x1
and x2
both hold references to that object, so id(x1)
and id(x2)
are the same memory address.id(x1) is id(x2)
is false because you called the id
function twice, and it returned two different copies of the integer 4461071152, so they aren't the same object at the same memory location (which is what is
tests).Amusingly enough, you can also do id(x1) is id(x1)
and the result is still False
, for exactly the same reason. The practical conclusion is that you should use ==
to compare integers, not is
.
Upvotes: 1
Reputation: 1723
The "is" operator in python checks if they point to the same object where as the "==" operator will check if the values are same.
l1 = [1,2]
l2 = [1,2]
print (l1 == l2) #return true
print (l1 is l2) #returns false
When you do id(x1) is id(x2) its 2 temporary objects with different identity.
Upvotes: 0