Python – “is not” operator
In Python, is not Operator is used to check if two variables does not have the same object.
Python is not Operator is an identity operator, because, it compares objects if they are not same. And it is just the inverse of the Python is operator which you have learnt in the previous tutorial – Python is Operator.
The id property of the object is used for this comparison.
Syntax
The syntax to check if a
and b
does not have the same object is
a is not b
The above expression returns True if both a
and b
are not the same object, else it returns False.
Examples
1. When a and b are integers
In the following program, we take two numbers: a
, b
; assign them with same integer value, and check if both the variables do not hold the same object.
main.py
a = 5
b = 10
if (a is not b):
print("a and b do not hold the same object.")
else :
print("a and b hold the same object.")
Output
a and b do not hold the same object.
For integers, the id of the object is same as the integer value. Therefore, these two objects are not same.
2. When a and b are lists
In the following program, we take two lists in a
, b
with same elements.
main.py
a = [5, 10, 15]
b = [5, 10, 15]
if (a is not b):
print("a and b do not hold the same object.")
else :
print("a and b hold the same object.")
Output
a and b do not hold the same object.
Even though the two lists have same elements in the same order, their id values are different, and hence (a is not b
) is true.
Now, let us create a variable c
from a
using Assignment operator =
, and check if a
and c
do not hold the same object.
main.py
a = [5, 10, 15]
c = a
if (a is not c):
print("a and c do not hold the same object.")
else :
print("a and c hold the same object.")
Output
a and c hold the same object.
While assigning the value in a variable to another variable, the same object is assigned to the new variable. Thus the two variables hold the same object.
You can check the working of this is not operator with other data types, or user defined types.
For the above two programs, you may print the id property of the objects, and then you get a clear idea of comparison used in is not operator.
main.py
a = [5, 10, 15]
b = [5, 10, 15]
c = a
print('id of a:', id(a))
print('id of b:', id(b))
print('id of c:', id(c))
Output
id of a: 140453705373056
id of b: 140453704467584
id of c: 140453705373056
The id of a
and c
are same, but that of a
and b
are different.
Conclusion
In this Python Tutorial, we learned about is not Operator, its syntax, and usage, with examples.