Difference between Equality Operator and Identity Operator in Python

Mridu Bhatnagar
InstructorMridu Bhatnagar

Share this video with your friends

Send Tweet
Published 4 months ago
Updated 3 months ago

Use the equality operator to compare the values of the objects. Identity operator is used to verifying that objects are equal but are not referring to the same object in memory.

Use cases where identity operator is used are:

  • to test if the object is None
  • to test if the object is of a particular type or not

There may be use cases where the output returned by both the operators is the same. But, in your program, you have used the identity operator instead of the equality operator.

To avoid such mistakes it is important to understand the difference between identity and equality operator.

Instructor: [0:03] Let us try to understand the difference between = versus == operator.

[0:14] We have a list L having elements 1, 2, 3 inside of it. We have a list L1 having 2, 3, 4 in it. To compare the values of both the list, we can do L == L1. You see the result returned is false. The result returned is false because value of both the objects is different.

[0:45] Our first one is list object having elements 1, 2, 3. L1 is our second object having elements 2, 3, 4. Both the lists are different.

[1:01] While instead of ==, if mistakenly you use =, then let us see what will happen. L = L1. This also returned a result as false. This time the result is false because = operator compares the address of object in memory.

[1:23] Address of object L is this. Likewise, address of L1 is this. Both the addresses are different. That is why the returned result is false. That is why it is important to know the difference between the two operators.

[1:48] If you end up using interchangeably, then in your program no error would get raised because of this minor mistake. It is something that you yourself will have to check and debug.