0

I know that the operators is and is not test for object identity: x is y is true if and only if x and y are the same object

I initialize two variables i and j with the same value 10, and when I am comparing the id of both variable with is operator it gives me a False even though the id(i) and id(j) are the same.

I need a clarification, Here is my code

>>> i = 10;
>>> j = 10;
>>> print(10==10);
True
>>> print(id(10)==id(10));
True
>>> print(10 is 10);
True
>>> print(5+5 is 10);
True
>>> print(i == j);
True
>>> print(id(i) == id(j));
True
>>> print(i is j);
True
>>> print(id(i) is id(j)); # Why this statment Evaluate to False this is my quetion?
False
>>> id(i);
140718000878704
>>> id(j);
140718000878704
smci
  • 32,567
  • 20
  • 113
  • 146
4nkitpatel
  • 148
  • 2
  • 12
  • Possible duplication of https://stackoverflow.com/questions/132988/is-there-a-difference-between-and-is – ComplicatedPhenomenon Aug 03 '19 at 05:48
  • 1
    specifically this is answered here: https://stackoverflow.com/a/1085656/1240268 (small integers are cached and so the same object, large integers are not the same object) – Andy Hayden Aug 03 '19 at 06:03
  • Because you're confusing how to use `is`-operator. **Either you test `x is y` or you test `id(x) == id(y)`, but don't throw both into one expression: `id(x) is id(y)` makes no sense**: it would mean testing `id(id(x)) == id(id(y))` – smci Aug 03 '19 at 11:06

1 Answers1

1

The is check is True if and only if the id()s are equal--if they are the same object in memory. (The id() builtin gets a unique integer identifier for the object, which is based on its memory address in CPython).

It is improper to use an is check on integers to compare their values. CPython does re-use integer objects in a small range instead of making new ones as an optimization, but this is an implementation detail that you should not rely upon.

For integer objects outside of that range, they may be separate objects in memory, even if they are equal in value.

For example,

>>> x = -6
>>> -6 is x
False
>>> x = 257
>>> 257 is x
False
gilch
  • 10,813
  • 1
  • 23
  • 28
  • @4nkit_patel That's because `-5` is inside that small range I mentioned where CPython re-uses the objects. That's why I used a `-6` :) – gilch Aug 03 '19 at 06:04
  • If I Do `>>> x = -5 >>> -5 is x True` this is true because you told CPython does re-use integer objects in a small range ?? – 4nkitpatel Aug 03 '19 at 06:05