3

I'm trying to compare variables using is operator. Here's what I've done

def get_no():
    return 1234

a = get_no()
b = 1234
c = 1234
print(a is 1234) #False
print(a is b)    #False
print(b is c)    #True

a is b is expected to be False as both are pointing to different values. But, why is b is c returning True ?. Why is the function get_no() causing a difference here?

Ashoka Lella
  • 6,631
  • 1
  • 30
  • 39

1 Answers1

0

Python is tests for object identity, not value equality. Use == to compare values.

As for the example case, it's because of how Python treats some values under the hood. On my system, for example, the integer value of 5 is actually the same object, while 1234 is a different object. You can verify this using the built-in id function.

>>> a = 5
>>> b = 5
>>> a is b
True
>>> id(a)
25769987752
>>> id(b)
25769987752

>>> a = 1234
>>> b = 1234
>>> a is b
False
>>> id(a)
25770739272
>>> id(b)
25770390520

This may be because of some internal optimizations in Python and apparently can vary between environments.

The bottom line is, is shouldn't be used for value comparison for this very reason, even if it works "well" in some cases.

famousgarkin
  • 13,687
  • 5
  • 58
  • 74
  • @Christian Added the relevant explanation. – famousgarkin Jun 06 '14 at 07:45
  • 1
    Well, I'm very intrigued. When I do `b = $` and `c = $` for **any** integer (including `500`), I get `True`. – Christian Tapia Jun 06 '14 at 07:46
  • @Christian I did some testing. For me the only integers that result in `True` are -5 to 256, which proves the point that `is` is "unpredictable" (as far as common use goes) for value comparison and shouldn't be misused for that. – famousgarkin Jun 06 '14 at 08:07
  • I just realized that in an interactive session the result is `True` only for integers from -5 to 256, but on a script it works for any integer. – Christian Tapia Jun 06 '14 at 08:15
  • @Christian For me it is actually consistent using either REPL or a script, no difference. I improved on the answer with these findings. – famousgarkin Jun 06 '14 at 08:22