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
• 5,870 points
60 views

1 answer to this question.

Your answer

Your name to display (optional):
Privacy: Your email address will only be used for sending these notifications.
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
• 9,300 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
• 56,100 points
27 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
• 56,100 points
91 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,500 points
13 views
0 votes
1 answer

Difference between append vs. extend list methods in Python

append: Appends object at end. x = [1, ...READ MORE

answered Jun 4, 2018 in Python by ariaholic
• 7,320 points
106 views
0 votes
1 answer

how can i count the items in a list?

suppose you have a list a = [0,1,2,3,4,5,6,7,8,9,10] now ...READ MORE

answered May 2 in Python by Mohammad
• 920 points
18 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
• 9,300 points
6 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
• 9,300 points
4 views

© 2018 Brain4ce Education Solutions Pvt. Ltd. All rights Reserved.
"PMP®","PMI®", "PMI-ACP®" and "PMBOK®" are registered marks of the Project Management Institute, Inc. MongoDB®, Mongo and the leaf logo are the registered trademarks of MongoDB, Inc.