Identity operators
Identity operators are used to check if two variables or two values are located at the same memory location.
Here is the list of identity operators in Python.
Operator |
Meaning |
Example |
is |
True if two operands are identical (refer to the same object) |
x is True |
is not |
True if two operands are not identical (do not refer to the same object) |
x is not True |
Note: If two variables are equal, it does not imply that they are identical.
Example : Identity operators
value1 = 1
value2 = 2
string1 = 'Python'
string2 = 'Python'
list1 = [1,2,3]
list2 = [1,2,3]
print(value1 is value2)
# Output: False
print(string1 is string2)
# Output: True list2)
print(list1 is list2)
# Output: False
print(list1 is not list2)
# Output: True
Output
False
True
False
True
Here, value1 and value2, string1, and string2 have the same identity since they share the same location. The list1 and list2 are equal but not identical. To verify the same we can check their identity using id() function as shown below.
print(id(value1))
#Output: 1672071312
print(id(value2))
#Output: 1672071312
print(id(string1))
#Output:21102080
print(id(string2))
#Output: 21102080
print(id(list1))
#Output: 62238968
print(id(list2))
#Output: 62239248
Output
1672071312
1672071312
21102080
21102080
62238968
62239248