Python Tutorial Python Advanced Python References Python Libraries

Python - Identity Operators



Identity operators are used to compare the objects. It returns true if the variables on either side of the operator point to the same object, otherwise returns false. Python supports two identity operators:

  • is - Returns true if the variables on either side of the operator point to the same object, otherwise returns false.
  • is not - Returns false if the variables on either side of the operator point to the same object, otherwise returns true.

Example: is operator

In the example below, the is operator is used to check the type of a given variable.

MyNum = 10
MyList = [10, 20, 30, 40]

#checking MyNum for int type
if type(MyNum) is int:
  print("MyNum is a int value.")
else:
  print("MyNum is not a int value.")

#checking MyList for list type
if type(MyList) is list:
  print("MyList is a list.")
else:
  print("MyList is not a list.")

The output of the above code will be:

MyNum is a int value.
MyList is a list.

Example: is not operator

In the example below, the is not operator is used to check the type of a given variable.

MyNum = 10
MyList = [10, 20, 30, 40]

#checking MyNum for float type
if type(MyNum) is not float:
  print("MyNum is not a float value.")
else:
  print("MyNum is a float value.")

#checking MyList for tuple type
if type(MyList) is not tuple:
  print("MyList is not a tuple.")
else:
  print("MyList is a tuple.")

The output of the above code will be:

MyNum is not a float value.
MyList is not a tuple.

❮ Python - Operators