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?
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?
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