Erratic behavior of "is" expressions in python.
>>> 258 -1 is 257
False
And
>>> 258 -1 == 257
True
How is python evaluating "is" expression ? and why does it show it as false , eventhough it is true ?
Why is it happening only to certain set of numbers ?
2 - 1 is 1 True
works perfectly fine.
You can use the built-in Python eval() to dynamically evaluate expressions from a string-based or compiled-code-based input. If you pass in a string to eval() , then the function parses it, compiles it to bytecode, and evaluates it as a Python expression.
In the last two examples, the left operand is false (an empty object). The Python or operator evaluates both operands and returns the object on the right, which may evaluate to either true or false.
Booleans are numeric types, and True is equal to 1 . So True < 1 is the same as 1 < 1 . Since this is a strict inequality, and 1 == 1 , it returns False.
The == operator compares the value or equality of two objects, whereas the Python is operator checks whether two variables point to the same object in memory. In the vast majority of cases, this means you should use the equality operators == and != , except when you're comparing to None .
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
andis not
test for object identity:x is y
istrue
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With