Is there a difference, in the way python does the comparing, between:
if x == 0.0:
print "x is zero"
and
if not x:
print "x is zero"
that would make one preferred to the other?
Is there a difference, in the way python does the comparing, between:
if x == 0.0:
print "x is zero"
and
if not x:
print "x is zero"
that would make one preferred to the other?
Just complementing the comments above, here is the bytecode:
In [10]: dis.dis(is_zero_equal_sign)
2 0 LOAD_FAST 0 (x)
3 LOAD_CONST 1 (0)
6 COMPARE_OP 2 (==)
9 POP_JUMP_IF_FALSE 20
3 12 LOAD_CONST 2 ('zero')
15 PRINT_ITEM
16 PRINT_NEWLINE
17 JUMP_FORWARD 0 (to 20)
>> 20 LOAD_CONST 0 (None)
23 RETURN_VALUE
In [11]: dis.dis(is_zero_no_equal_sign)
2 0 LOAD_FAST 0 (x)
3 POP_JUMP_IF_TRUE 14
3 6 LOAD_CONST 1 ('zero')
9 PRINT_ITEM
10 PRINT_NEWLINE
11 JUMP_FORWARD 0 (to 14)
>> 14 LOAD_CONST 0 (None)
17 RETURN_VALUE
Looking at the bytecode it seems like the difference is basically insignificant in terms of performance. When using the equal sign CPython still has to load 0 as a constant and the comparison process is slightly different. If you simply want the one with less steps, you can use the one without '=='.