Python NOT EQUAL operator
In this article, we are going to see != (Not equal) operators. In Python != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal.
Note: It is important to keep in mind that this comparison operator will return True if the the values are same but are of different data types.
Syntax: Value A != Value B
Example 1: Comparing different values of the same data type
Python3
A = 1B = 2C = 2print(A!=B)print(B!=C) |
Output:
True False
Example 2: Comparing same values of different data type
Python3
A = 1B = 1.0C = "1"print(A!=B)print(B!=C)print(A!=C) |
Output:
False True True
Example 3: Python not equal with custom object
The __ne__() gets called whenever the not equal operator is used. We can override this function to alter the nature of the not equal operator.
Python3
class Student: def __init__(self, name): self.student_name = name def __ne__(self, x): # return true for different types # of object if type(x) != type(self): return True # return True for different values if self.student_name != x.student_name: return True else: return Falses1 = Student("Shyam")s2 = Student("Raju")s3 = Student("babu rao")print(s1 != s2)print(s2 != s3) |
Output:
True True
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning – Basic Level Course


