Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does python evaluate "is" expressions? [duplicate]

Tags:

python

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.

like image 565
Rahul Avatar asked May 17 '13 18:05

Rahul


People also ask

How does Python evaluate mathematical expressions?

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.

Does Python evaluate both sides of or?

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.

Does 1 == true evaluate true or false in Python?

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.

What does == mean in Python?

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 .


1 Answers

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
like image 114
Ashwini Chaudhary Avatar answered Sep 21 '22 05:09

Ashwini Chaudhary