Python Identity Operator

The Python Identity operator will compare the objects by checking if the object belongs to the same memory location. Read this article to learn more about Python Identity Operator.

What is Python Identity Operator

Python operator consists of two operators such as ‘is‘and ‘is not‘. Both the values will be returned with the Boolean values. The in-operators will check if the value comes true only if the operand object shares the same memory location.

Furthermore, the memory location of the object will be achieved with the help of the ”id()” function. Whereas, if both the variables id() are the same, then the in operator will return with the True.

# Identity Operator - 'is'
x = [1, 2, 3]
y = [1, 2, 3]
z = x

# 'is' operator checks if both variables refer to the same object in memory
print(x is y)  # False, because x and y refer to different objects
print(x is z)  # True, because x and z refer to the same object

# Identity Operator - 'is not'
print(x is not y)  # True, because x and y do not refer to the same object
print(x is not z)  # False, because x and z refer to the same object

Output

False
True
True
False

However, list and tuple will do operations very differently. The example given below contains two lists such as ”a” and ”b” with the same items and the id() varies.

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)

Output

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

The list or tuple has memory locations of individual items only and not the items themselves. Thus, ”a ” consists of an address of 10,20, or 30 integer objects that are located in a particular location and will be different from the of ”b”.

Output

140734682034984 140734682035016 140734682035048
140734682034984 140734682035016 140734682035048

Here, the ‘is’ operator will return with a false value even if it contains the same numbers. This happens due to the two different locations of a and b.

Conclusion

To conclude, this article will improve our knowledge of the Python Identity Operator. It has also provided examples of the ”is” and ”is not” operators.

Python Identity Operator- FAQs

Q1. What is an identity operator in Python?

Ans. Python Identity operator is considered as the special comparison operator to find if the two variables have the same object in the memory.

Q2. What is the symbol for the identity operator?

Ans. d will stand for the identity function and I for the identity matrix

Q3. What is ID in Python for example?

Ans. The id method will return a unique integer number for every unique value it will be worked with.

Hridhya Manoj

Hello, I’m Hridhya Manoj. I’m passionate about technology and its ever-evolving landscape. With a deep love for writing and a curious mind, I enjoy translating complex concepts into understandable, engaging content. Let’s explore the world of tech together

Leave a Comment