@jonrsharpe has an excellent explanation of what's going on. I thought I'd just show the difference in time when running each of the 3 options 10,000,000 times (enough for a slight difference to show).
Code used:
def a(x):
if x != 'val':
pass
def b(x):
if not x == 'val':
pass
def c(x):
if x == 'val':
pass
else:
pass
x = 1
for i in range(10000000):
a(x)
b(x)
c(x)
And the cProfile profiler results:
So we can see that there is a very minute difference of ~0.7% between if not x == 'val':
and if x != 'val':
. Of these, if x != 'val':
is the fastest.
However, most surprisingly, we can see that
if x == 'val':
pass
else:
is in fact the fastest, and beats if x != 'val':
by ~0.3%. This isn't very readable, but I guess if you wanted a negligible performance improvement, one could go down this route.