Identity operators in Python

 Python Identity operators

Identity operators are used to compare objects.


In Python, if two variables has same value then they will share the same memory location (id).


To check the id (memory address of object), which is unique for all objects in Python, use id() function.


And in Python everything is an object.


Python Identity operators.


OperatorOperation
isReturns True if both the variables
points to same object
is notReturns True if both the variables
points to different objects


Python 'is' and 'is not' identity operator

In Python, if the variables have same value then they will have same id. 

Yields True on, performing 'is' operation on two identical objects. And performing 'is not' operation on two identical objects yields False.


Program

>>> a = 1
>>> b = 1
>>> z = a
>>> a is z
True
>>> a is b
True
>>> z is b
True
>>> id(a) == id(b) and id(a) == id(z) and id(b) ==id(z)
True

>>> A = 2
>>> A is not a
True



Conclusion

Identity operators are used to compare objects.

Returns True if both the objects are the same, while working with 'is' operator.

And '==' operator returns True if value of both the objects are same.





Previous                          Next

If you have any query, feel free to ask.

إرسال تعليق

If you have any query, feel free to ask.

Post a Comment (0)