Python Identity Operators

Identity operators are used to compare the memory location of two objects, especially when both the objects have same name and can be differentiated only using its memory location. There are two Identity operators: "is" and "is not" .
  1. is - Returns true if both variables are the same object.
  2. is not - Returns true if both variables are not the same object.
x is y is true if and only if x and y are the same object . Object identity is determined using the id() function . x is not y yields the inverse truth value.
Python Identity Operators

Python is operator

x = '101' y = '101' z = '102' if (x is y): print ('x is y') else: print ('x is not y') if (x is z): print('x is z') else: print ('x is not z') if (y is z): print('y is z') else: print ('y is not z')
output
x is y x is not z y is not z

Python is not Operator

x = '101' y = '101' z = '102' if (x is not y): print ('x is not y') else: print ('x not y') if (x is not z): print ('x is not z') else: print ('x is z') if (y is not z): print ('y is not z') else: print ('y is z')
output
x not y x is not z y is not z

Is there a difference between "==" and "is"?

The is operator will return True if two variables point to the same object, "==" if the objects referred to by the variables are equal: for example in this case num1 and num2 refer to an int instance storing the value 101:
num1 = 101 num2 = num1

difference between

Because num2 refers to the same object is and == will give True:

>>> num1 == num2 True >>> num1 is num2 True

In the following example the names num1 and num2 refer to different int instances, even if both store the same integer:

>>> num1 = 101 >>> num2 = 101

python is operator
Because the same value (integer) is stored == will return True, that's why it's often called value comparison . However is operator will return False because these are different objects :
>>> num1 == num2 True >>> num1 is num2 False

You should only use is operator if you:

  1. want to check if two objects are really the same object (not just the same "value").
  1. want to compare a value to a Python constant.
The constants in Python are:
  1. None
  2. True
  3. False
  4. NotImplemented
  5. Ellipsis
  6. __debug__
  7. classes (for example int is int or int is float)