-4
id(5) is id(5)  #returned False
id(5) == id(5)  #returned True

is operator returns true if the operands points the same object. Here it is pointing to the same object (i.e., 5). But here, it is returned as False. What's the reason behind that?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • Because you're not comparing 5, you're comparing *the ID of 5*. – jonrsharpe Sep 06 '20 at 12:41
  • Try doing `print(type(id(5)))`. I will give you a hint: the ID itself is just an int. And for that you can refer to https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers – Tomerikoo Sep 06 '20 at 12:43
  • 1
    Does this answer your question? [Is there a difference between "==" and "is"?](https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is) – s3cret Sep 06 '20 at 12:44

1 Answers1

0

To start, CPython caches small int values, so the same object is always used for 5.

id(5), however, returns a large int value (e.g., id(5) == 4431761200). This value is not cached, so it's possible that two calls to id(5) may or may not produce the same object representing that value. In the expressions id(5) is id(5) and id(5) == id(5), if the large object isn't cached, there are necessarily two distinct objects, because both objects have to be live until is or == completes its comparison.

Note that in some situations, it might look like an object is cached, for example,

>>> id(id(5))
4434162352
>>> id(id(5))
4434162352

But this is just a case where the same identifier is being reused for two objects whose lifetimes don't overlap.

>>> x = id(5)
>>> y = id(5)
>>> x == y
True
>>> id(x) is id(y)
False
>>> id(x) == id(y)
False
chepner
  • 497,756
  • 71
  • 530
  • 681