Skip to content
Advertisement

Python if not == vs if !=

What is the difference between these two lines of code:

JavaScript

and

JavaScript

Is one more efficient than the other?

Would it be better to use

JavaScript

Advertisement

Answer

Using dis to look at the bytecode generated for the two versions:

not ==

JavaScript

!=

JavaScript

The latter has fewer operations, and is therefore likely to be slightly more efficient.


It was pointed out in the commments (thanks, @Quincunx) that where you have if foo != bar vs. if not foo == bar the number of operations is exactly the same, it’s just that the COMPARE_OP changes and POP_JUMP_IF_TRUE switches to POP_JUMP_IF_FALSE:

not ==:

JavaScript

!=

JavaScript

In this case, unless there was a difference in the amount of work required for each comparison, it’s unlikely you’d see any performance difference at all.


However, note that the two versions won’t always be logically identical, as it will depend on the implementations of __eq__ and __ne__ for the objects in question. Per the data model documentation:

There are no implied relationships among the comparison operators. The truth of x==y does not imply that x!=y is false.

For example:

JavaScript

Finally, and perhaps most importantly: in general, where the two are logically identical, x != y is much more readable than not x == y.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement