Python identity operator

Python Identity Operators

Python has two identity operators: is and is not. Both return opposite Boolean values. The “in” operator returns True when the operand objects share the same memory location. The object’s memory location can be retrieved using the “id()” function. If the id() values of two variables are the same, the “in” operator returns True (thus, is not returns False).

a="TutorialsPoint"
b=a
print ("id(a), id(b):", id(a), id(b))
print ("a is b:", a is b)
print ("b is not a:", b is not a)

This will produce the following output −

id(a), id(b): 2739311598832 2739311598832
a is b: True
b is not a: False

It may seem strange at first glance that lists and tuples are different objects. In the following example, the two lists “a” and “b” contain the same items. However, their id() values are different.

a=[1,2,3]
b=[1,2,3]
print ("id(a), id(b):", id(a), id(b))
print ("a is b:", a is b)
print ("b is not a:", b is not a)

It produces the following output −

id(a), id(b): 1552612704640 1552567805568
a is b: False
b is not a: True

A list or tuple contains only the memory locations of the individual items, not the items themselves. Thus, the variable “a” contains the addresses of the integer objects 10, 20, and 30 at a location that may be different from the location of the variable “b.”

print (id(a[0]), id(a[1]), id(a[2]))
print (id(b[0]), id(b[1]), id(b[2]))

This will produce the following output: Output

140734682034984 140734682035016 140734682035048
140734682034984 140734682035016 140734682035048

Because the positions of “a” and “b” are different, the “is” operator will return False even if the two lists contain the same number.

Leave a Reply

Your email address will not be published. Required fields are marked *