Mr Korni
Mr Korni

Reputation: 41

What is the difference between "not ==" and "!="?

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 "!="?

Upvotes: 4

Views: 1030

Answers (3)

MSeifert
MSeifert

Reputation: 152587

These statements are equivalent as long as == returns the logical inverse of !=. For most data types this is a valid assumption, however Python allows to implement == and != specifically (__eq__ for == and __ne__ for !=). So it really depends on the data type you're using.

And == and != may not even return booleans, they don't even have to return the same data type. Which opens up another possibility to customize the result: Via truth value testing, which can be customized (besides others) by the __bool__ (or __nonzero in Python 2) method.

However for integers both of your approaches are equivalent. However I would always use the != approach. It's clearer about the intent and shorter.

Just to give you an example where the statements are not equivalent, let's take a data type such as NumPy arrays (just to name a popular data structure that implements the operators differently) that implements == and != to return another NumPy array containing booleans and also implements __bool__ to throw an Exception:

>>> import numpy as np
>>> np.array([1,2,3]) != np.array([3,3,3])
array([ True,  True, False])

>>> not np.array([1,2,3]) == np.array([3,3,3])
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()

But if you used any of these in an if both would raise the Exception.

Upvotes: 4

Antony Waiganjo
Antony Waiganjo

Reputation: 23

As you can see with the outcome, both mean the same thing, checking if one value is different from the other, it's a matter of preference...

Upvotes: -2

wim
wim

Reputation: 362478

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

Upvotes: 3

Related Questions