In this section, we will learn what identity operators are and how to use them in Python.
Note: we’re assuming you already familiar with operators in general.
What is Identity Operator in Python?
The identity operator is used to see if two object values are the same (they are both located in the same memory location).
The identity operators take two operands. These operands are the values (objects) that we want to see if they are equal (they both live in the same memory location).
Note: the return value of an identity operator is a boolean value.
List of Identity Operators in Python
Here’s the list of identity operators in Python:
Operator | Description |
is | Using this operator, we can see if two values are the same (live in the same memory location). |
is not | Using this operator, we can see if two values are not the same! (They live in two separate memory location). |
Python is Operator
The `is` operator is used to see if two values are equal and they are stored in the same memory location or not.
If both are coming from the same memory space, then the return value of this operator will be True. Otherwise the value False will return instead.
Python is Operator Syntax
Left-Operand is Right-Operand
Python is Operator Example
d = [1,2,3,4,5] a = [1,2,3,4,5] if d is a: print("The a and d variables are pointing to the same memory location")
Output:
Note: In this example, the variable `a` and `d` both have the same set of elements, but each of these values is stored in a separate memory location. For this reason, the result of calling the `is` operator will be False and hence the body of the `if` statement did not execute.
But if we use the equal operator `==`, the result will be True because this operator only checks the actual values to see if they are equal or not. It doesn’t care about the memory location of the involved objects.
Example: using equal operator in Python
d = [1,2,3,4,5] a = [1,2,3,4,5] if d == a: print("The a and d variables are equal in values")
Output:
The a and d variables are equal in values
Python is not Operator
The `is not` operator is used to see if two values are not stored in the same memory space.
If they were in two different and independent memory locations, then the result of this operator will be True. Otherwise the value False will return as a result.
Python is not Operator Syntax
value is not data-type
Example: using Python is not operator
d = 50 a = 50 if d is not a: print("The a and d variables are not pointing to the same memory space").
Output:
Note that here, the `a` and `d` variables are pointing to the same memory space where the value 50 is stored. But because we used the `is not` operator, then the result of this condition is False and so the body of the if statement did not execute.