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 29, 2019 in Python by ana1504.k
• 7,910 points
952 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 29, 2019 by SDeb
• 13,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
• 58,020 points
804 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
• 58,020 points
2,662 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, 2019 in Python by Nymeria
• 3,560 points
11,309 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, 2019 in Python by Jason
7,225 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,454 views
0 votes
1 answer
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, 2019 in Python by SDeb
• 13,300 points
581 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, 2019 in Python by SDeb
• 13,300 points
1,128 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP