简体   繁体   中英

Why aren't id(x1) and id(x2) the same?

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 ?

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:

  • 51 is a small integer so there's only one object representing it.
  • x1 and x2 both hold references to that object, so id(x1) and id(x2) are the same memory address.
  • That memory address is a rather large number - 4461071152 when you tested it - so if it appears more than once in the program then you will usually get different copies of it at different memory locations.
  • So 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 .

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM