Identity operators in Python allow us to verify if two variables refer to the same object in memory. These operators are useful for comparing object identity (i.e., whether two variables point to the same location in memory).
The is and is not operators are very efficient as they simply compare the memory addresses of two objects (they do not perform any additional operations).
| Operator | Name | Description |
|---|---|---|
is | Is | Verifies if two variables point to the same object |
is not | Is not | Verifies if two variables do not point to the same object |
List of identity operators
Operator is
The is operator is used to verify if two variables refer to the same object in memory.
a = [1, 2, 3]
b = a
is_equal = (a is b) # True, since a and b refer to the same object
In this example, both a and b point to the same object in memory, so the expression a is b is True.
Operator is not
The is not operator is used to verify if two variables do NOT refer to the same object in memory.
x = 10
y = 10
is_not_equal = (x is not y) # False, since x and y refer to the same object
In this example, both x and y point to the same object in memory (in Python, small integers are stored in the same location), so the expression x is not y is False.
Usage examples
Variable Identity Verification
x = 100
y = x
are_equal = (x is y) # True, since x and y are the same object in memory
List Identity Verification
list1 = [1, 2, 3]
list2 = [1, 2, 3]
list3 = list1
are_equal = (list1 is list2) # False, since list1 and list2 are not the same object
are_equal2 = (list1 is list3) # True, since list1 and list3 are the same object
Object Identity Verification
class MyClass:
pass
object1 = MyClass()
object2 = MyClass()
object3 = object1
are_equal = (object1 is object2) # False, since object1 and object2 are not the same object
are_equal2 = (object1 is object3) # True, since object1 and object3 are the same object
