>> 258 -1 is 257 False and >>> 258 -1 == 257...">

How does python evaluate "is" expressions?

Erroneous behavior of "is" expressions in python.

>>> 258 -1 is 257 False 

and

 >>> 258 -1 == 257 True 
  • How does python evaluate the expression is? and why does he show it as false, although it is true?

  • Why does this happen only with a certain set of numbers?

    2 - 1 equals 1 True

works great.

+6
source share
4 answers

is used to verify identity, to check whether both variables point to the same object, and == used to verify values.

From docs :

The is and is not operators check the identifier of an object: x is y - true if and only if x and y are the same object. x is not y gives 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 
+6
source

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 .

+2
source

The is operator checks the identifier of an object: the object created by the call 258-1 is not the same object as the created 257 . The == operator checks if the values โ€‹โ€‹of the compared objects match.

Try using help('is') .

+2
source

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.

+1
source

Source: https://habr.com/ru/post/945289/


All Articles