-1
a = "test"
b = a
c=id(a)
d=id(b)

print("a == b:",a == b)
print("a is b:",a is b)
print(id(a), id(b))
print("id(a) is id(b):",id(a) is id(b))
print("id(a) == id(b):",id(a) == id(b))
print(c, d)
print("c is d:",c is d)
print("c == d:",c == d)

----------result----------

a == b: True
a is b: True
1843108275696 1843108275696
id(a) is id(b): False
id(a) == id(b): True
1843108275696 1843108275696
c is d: False
c == d: True

Why does id(a) is id(b) have false?
I expecte id(a) is id(b) True

tora
  • 17
  • 3
  • Possible duplicate of [Python string interning](https://stackoverflow.com/q/15541404/11082165) and ["is" operator behaves unexpectedly with integers](https://stackoverflow.com/q/306313/11082165) – Brian61354270 Jan 16 '23 at 02:55

2 Answers2

0

Even id(a) and id(a) are different (when compared with is) because they are different objects of type int. Only very small absolute values of int are the same object:

>>> int(str(2 ** 6)) is int(str(2 ** 6))
True
>>> int(str(2 ** 16)) is int(str(2 ** 16))
False

The int(str(...)) conversion is needed to prevent interning of identical int literals by Python 3.7+.

The result of id is usually a large int:

>>> id("test")
140023900375784

By saying o1 and o2 are different objects I mean that the they are not stored at the same memory address.

pts
  • 80,836
  • 20
  • 110
  • 183
0

is compares the memory addresses of the objects a and b. They are different in your case and would be false.

More: The is keyword is used to test if two variables refer to the same object.

Docs: https://www.w3schools.com/python/ref_keyword_is.asp

iohans
  • 838
  • 1
  • 7
  • 15