I was looking at google, but I could not find an answer.
if 5 != 10:
print('True')
# True
if not 5 == 10:
print('True')
# True
Both seem to do the same. When to use "not ==
" and when to use "!=
"?
In the case of a comparison with two integers, they are the same. Prefer !=
as more pythonic.
The result may differ if either operand is an instance of a custom class. Custom classes are free to override ==
and !=
operator independently (even with insane results)
From the LHS:
>>> class A:
... def __eq__(self, other):
... return False
... def __ne__(self, other):
... return False
...
>>> a = A()
>>> a != 5
False
>>> not a == 5
True
From the RHS:
>>> class R(str):
... def __eq__(self, other):
... return False
... def __ne__(self, other):
... return False
...
>>> r = R()
>>> 'spam' != r
False
>>> not 'spam' == r
True