How does python evaluate "is" expressions?
is used to verify identity, to check whether both variables point to the same object, and == used to verify values.
From docs :
The
isandis notoperators check the identifier of an object:x is y-trueif and only if x and y are the same object.x is not ygives the opposite value of truth.
>>> 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 the object 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 (from -5 to 256) and small lines are cached by Python: Why is (0-6) -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 is compares the identifier of the object and gives True only if both sides are the same object. For performance reasons, Python maintains the "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 implementation detail, so you should not rely on it. If you want to compare equality, use == rather than is .
The Python is statement checks the identifier of an object, not the value of an object. Two integers must reference the same actual object inside in order to return true.
This will return true for "small" integers due to the internal cache supported by Python, but two numbers with the same value will not return true when compared to is in general.