7

Erratic behavior of "is" expressions in python.

>>> 258 -1 is 257
False

And

>>> 258 -1 == 257
True
  1. How is python evaluating "is" expression ? and why does it show it as false , eventhough it is true ?

  2. Why is it happening only to certain set of numbers ?

    2 - 1 is 1 True

works perfectly fine.

Rahul
  • 11,129
  • 17
  • 63
  • 76

4 Answers4

6

is is used for identity check, to check if both variables point to the same object, while == is used for checking values.

From the docs:

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. x is not y yields the inverse truth value.

>>> id(1000-1) == id(999)
False

""" What is id?
id(object) -> integer
Return the identity of an object. This is guaranteed to be unique among
simultaneously existing objects. (Hint: it's the object's memory address.)
"""

>>> 1000-1 is 999
False
>>> 1000-1 == 999
True
>>> x = [1]
>>> y = x    #now y and x both point to the same object
>>> y is x
True
>>> id(y) == id(x)
True
>>> x = [1]
>>> y = [1]
>>> x == y
True
>>> x is y
False
>>> id(x),id(y)       #different IDs
(161420364, 161420012) 

But some small integers(-5 to 256) and small strings are cached by Python: Why (0-6) is -6 = False?

#small strings
>>> x = "foo"
>>> y = "foo"
>>> x is y
True
>>> x == y
True
#huge string
>>> x = "foo"*1000
>>> y = "foo"*1000
>>> x is y
False
>>> x==y
True
Community
  • 1
  • 1
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
2

is compares object identity and yields True only if both sides are the same object. For performance reasons, Python maintains a "cache" of small integers and reuses them, so all int(1) objects are the same object. In CPython, cached integers range from -5 to 255, but this is an implementation detail, so you should not rely on it. If you want to compare equality, use ==, not is.

kindall
  • 178,883
  • 35
  • 278
  • 309
  • You can also get that sort of thing happening with strings as string literals are cached up to a certain size. And things like `foo = "foo"; foo is foo.strip()` can return `True` as well. – mgilson May 17 '13 at 19:03
2

The is operator checks for object identity: the object created by calling 258-1 is NOT the same object as the one created by 257. The == operator checks if the values of the compared objects are the same.

Try using help('is').

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
Alice
  • 445
  • 1
  • 5
  • 18
1

The Python is operator checks for object identity, not object value. The two integers must refer to the same actual object internally for is to return true.

This will return true for "small" integers due to an internal cache maintained by Python, but two numbers with the same value will not return true if compared with is in general.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373