1
>> a=1
>> id(a);id(1)
1844525312
1844525312
>> id(a)==id(1)
True
>> id(a) is id(1)
False

what is the difference between the == and is?

Cleptus
  • 3,446
  • 4
  • 28
  • 34

2 Answers2

4

You are seeing the limit of Python's integer interning here. The CPython implementation keeps a pool of small int objects (-5 through 257) in memory and reuses them as much as possible. That is why id(a) and id(1) return the same value; both a and the literal 1 refer to the same object. That value, though, is a much larger integer (namely 1844525312). That means that Python is free to (and does) allocate separate int objects for the return value of id(a) and id(1), leading to the result you see. 1844525312 == 1844525312 is true, but id(a) and id(1) each return separate objects that represent the same value, leading to id(a) is id(1) returning false.

Note that with a = 1; id(a) == id(1) is not guaranteed to be true by Python itself; it's an implementation detail of a particular Python interpreter. It's allowed for an implementation to always allocate a new object for each new use, and it is allowed for an implementation to always reuse an existing object where possible. The only time Python guarantees that id(a) == id(b) for separate names a and b is if one name is assigned directly to the other (b = a or a = b).

chepner
  • 497,756
  • 71
  • 530
  • 681
  • You should use "is" instead of id()==id() because the second example can cause TOCTOU race condition when your program uses multiple threads. – Marat Mkhitaryan Sep 16 '21 at 13:30
  • It's a toy example demonstrating how the REPL interacts with interning; it doesn't need to worry about race conditions. – chepner Sep 16 '21 at 13:32
-1

The == operator compares by checking for equality:

The is operator, however, compares identities:

>> id(a)==id(1)

Since a=1 the value is same.

But for

>> id(a) is id(1)

Since id(a) and id(1) points to different objects, it is false! Hope it helped you.