If you have any query feel free to chat us!
Happy Coding! Happy Learning!
In Python, identity comparison operators are used to compare the identity of two objects. These operators check whether two variables or expressions refer to the same memory location (i.e., the same object) rather than comparing their values. There are two identity comparison operators in Python:
is
operator: Theis
operator returnsTrue
if two variables or expressions point to the same object, andFalse
otherwise.Example:
pythonCopy code
x = [1, 2, 3] y = x z = [1, 2, 3] print(x is y) # Output: True (x and y refer to the same list object) print(x is z) # Output: False (x and z refer to different list objects)
In this example,
x
andy
are two variables that both refer to the same list object, sox is y
returnsTrue
. On the other hand,x
andz
refer to two different list objects with the same values, sox is z
returnsFalse
.
is not
operator: Theis not
operator is the negation of theis
operator. It returnsTrue
if two variables or expressions point to different objects, andFalse
if they point to the same object.Example:
pythonCopy code
x = [1, 2, 3] y = x z = [1, 2, 3] print(x is not y) # Output: False (x and y refer to the same list object) print(x is not z) # Output: True (x and z refer to different list objects)
In this example,
x
andy
refer to the same list object, sox is not y
returnsFalse
. However,x
andz
refer to two different list objects with the same values, sox is not z
returnsTrue
.Identity comparison is different from value comparison (done using
==
operator). While==
checks if the values of two variables are equal,is
checks if the variables themselves point to the same object in memory. Be cautious when usingis
andis not
for mutable objects like lists, as their contents can change, affecting the results of identity comparison. For most cases, you will use==
for value comparison andis
for identity comparison with immutable objects like numbers, strings, and tuples.
Comments: 0