Python if not == vs if !=

0 votes
What is the difference between these two lines of code:

if not x == 'val':
and

if x != 'val':
Is one more efficient than the other?
Jan 28 in Python by ana1504.k
• 7,890 points
78 views

1 answer to this question.

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

not ==

  4           0 LOAD_FAST                0 (foo)
              3 LOAD_FAST                1 (bar)
              6 COMPARE_OP               2 (==)
              9 UNARY_NOT           
             10 RETURN_VALUE   
!=

  4           0 LOAD_FAST                0 (foo)
              3 LOAD_FAST                1 (bar)
              6 COMPARE_OP               3 (!=)
              9 RETURN_VALUE   
 

The latter has fewer operations, and is therefore likely to be slightly more efficient.
answered Jan 28 by SDeb
• 13,210 points

Related Questions In Python

0 votes
1 answer

Python 'If not' syntax

Yes, if bar is not None is ...READ MORE

answered Aug 1, 2018 in Python by Priyaj
• 57,300 points
61 views
0 votes
1 answer

Python `if x is not None` or `if not x is None`?

There's no performance difference, as they compile ...READ MORE

answered Sep 3, 2018 in Python by Priyaj
• 57,300 points
268 views
0 votes
1 answer

How do I check if input string is a valid regular expression or not in Python?

Hi. Good question! Well, just like what ...READ MORE

answered Feb 12 in Python by Nymeria
• 3,520 points
158 views
0 votes
1 answer

Open a file if it exists or create and open it does not exists - Python

You can use this: f = open("ex.txt","w+") Here the ...READ MORE

answered Jun 20 in Python by Jason
37 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 407 views
0 votes
1 answer

Which is better if we compare C vs Python?

It depends on what do you expect ...READ MORE

answered Mar 6 in Python by SDeb
• 13,210 points
27 views
0 votes
1 answer

How to get travis to fail if tests do not have enough coverage for python?

if you add the --fail-under switch to ...READ MORE

answered May 10 in Python by SDeb
• 13,210 points
96 views