In this post, we will see about Python not equal operator.
Not equal operator is denoted by !=
in Python and returns true when two variables are of same type but have different value. If two variable posses same value, then not equal operator will return False
.
Table of Contents
Python not equal operator example
Here is simple example of non equal operator
1 2 3 |
print(2.2!=2) |
This will print True.
1 2 3 4 5 6 7 8 |
str1 = "world" str2 = "world" str3 = "WORLD" print(str1!=str2) print(str1!=str3) |
Output:
True
str1!=str2 returns False:
As str1 and str2 are exactly same String, so it return False.
str1!=str3 returns True:
As str1 and str3 differ in case, it return True.
Please note that you can use <> for not equal in Python 2 but <> is deprecated in Python 3.
Python not equal operator in case of Custom object
When you call !=, python internally calls ne(self, other)
method. In case of custom objects, you can implement your own version in the class.
Here is quick example.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
class Country: name = '' population = 0 def __init__(self, name, population): self.name = name self.population = population def __ne__(self, other): # If different type, you can return true if type(other) != type(self): return True if self.name != other.name: return True else: return False india1 = Country('India', 1000) india2 = Country('India', 2000) china = Country('China', 3000) print(india1 != india2) print(india1 != china) |
Output:
True
As you can see, we have implemented ne(self, other)
and two countries are not equal, if there name are not same.
So that’s why
india1 != india2
returned False
as name is same in both objects even though population is different.
That’s all about Python not equal operator.