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?
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?
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.