1
var = False
if not var:
    do_thing()

or

var = False
if var == False:
    do_thing()

What is the difference between the two?(If there is one) Is one fast than the either?

ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
  • there's no practical difference; if you're interested in a super-precise analysis, you can use [dis](https://docs.python.org/2/library/dis.html) to see exactly how they each evaluate – Hamms Aug 05 '18 at 03:28
  • @user202729: This is about a boolean, not a string. – Ry- Aug 05 '18 at 03:29
  • 3
    The difference is that `not var` is readable and what people expect you to use, whereas `var == False` makes people wonder whether there’s some other falsy value you explicitly want to exclude by not using `not` (but not `0`, because `0 == False`). – Ry- Aug 05 '18 at 03:31
  • 1
    The differences start when your input is not a boolean – Mad Physicist Aug 05 '18 at 03:32

1 Answers1

3

Per PEP8 "Programming Recommendations":

Don't compare boolean values to True or False using ==.

  • Yes: if greeting:
  • No: if greeting == True:
  • Worse: if greeting is True:

Both of your tests happen to work here, but in general, using the implicit booleanness is considered more "Pythonic", since "truthy" vs. "falsy" is usually more important than True vs. False; if not var: will accurately identify var as falsy when it is None, or an empty sequence, which is usually what you want.

As far as performance goes, if not var: will be faster; if var == False: must load var and False, perform the comparison, then perform the implicit boolean test that if always performs; if not var: performs the implicit boolean test directly with no preamble.

Community
  • 1
  • 1
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271