Python Identity Operators


Python Identity Operators

The identity operators in python help determine whether some value belongs to a specific type or a class. They determine the type of data held by some variable. The identity operators, ‘is’ and ‘is not,’ are used for comparing the memory location of a given object. As soon as an object is created in the memory, it gets a unique memory address allocated to it. 
However, ‘==’ and ‘is’ are not the same ones. Also, ‘!=’ and ‘is not’ are also not the same. There have the following differences:

  • ‘==’ is used to compare if the object values are identical, and ‘is’ is used to compare if the object is of a given memory location.
  • ‘!=’ helps compare if the given object values are unequal, and ‘is not’ helps identify if the object does not belong to the exact memory location.

To find whether the two given objects have the same identity, you can use the ‘is’ and ‘is not’ operators in the if-else statements and then likewise print the results for both.

Identity operators compare the memory locations of two variables storing specific data.

                is

  Returns True if both variables contain the same value or object.

                is not

  Returns True if both variables do not contain the same value or object.


Example:

#is x = ["knowledge2life", "website"] y = ["knowledge2life", "knowledge2life"] z = x print(x is z) print(x is y) #is not x = ["knowledge2life", "website"] y = ["knowledge2life", "website"] z = x print(x is not z) print(x is not y)

OUTPUT:

True
False
False
True