Identity Operator in Python

Mridu Bhatnagar
InstructorMridu Bhatnagar

Share this video with your friends

Send Tweet
Published 4 months ago
Updated 3 months ago

The identity operator is used for checking whether the object is of the mentioned type.

Example:

>> a = "Hello World!"
>> type(a) is str
>> True

The result returned in the above case is true because the type of object is str.

Identity operator is also used to compare the object with None.

Example:

>> a = None
>> a is None
>> print(a)
>> True

Internally, the identity operator compares the memory address of the objects. Built-in id() method returns a unique number i.e address of the object in memory. If the address of both the objects in memory is the same identity operator returns the result as True.

Example:

>> a = 10
>> b = 10
>> a is b
>> True
>> id(a)
>> 916744
>> id(b)
>> 916744

The above code snippet tells us that value of both the objects is the same and variables a and b are referring to the same object in memory.

Instructor: [0:01] Identity operator in Python. Let us assign a variable A to an integer object, having value 10. Then we want to check whether the type of integer object is int or not. What we will do is we will do type(A) is int. Type is a built-in method used to check what is the type of object. Is, is our identity operator, and int is a shorthand for integer.

[0:40] The result returned by identity operator is true. Let us see what is happening under the hood. Is operator compares the address of the object, so we can do id(typeA). It returned us a memory address and likewise we can do id(int). It again returned us a memory address of the object. Both the memory addresses are same. That is why the returned result is true.

[1:19] Identity operator can also be used to check whether the value of object is none or not. We have a dictionary D, having key A value one, key B having value two. Suppose you are checking B.get. You want value corresponding to key C, and if key C does not exist, it should return none. When you do print X, it gives you the result as none.

[2:03] Now let us check whether the value of the object is none or not, so we can do X is none. This time the result returned is true. Let us again see why. We can do id(X). Id(X) gives us this memory address. Then we can do id(none). It returned us this memory address. Both the memory addresses are same. That means the result is true.