2

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?

DilithiumMatrix
  • 17,795
  • 22
  • 77
  • 119
izxle
  • 386
  • 1
  • 3
  • 19
  • `x = False` `if not x. . .` – Elliot Bonneville Nov 18 '15 at 22:02
  • 3
    If the value will only ever be numeric, then the main difference is readability. `if x == 0.0` makes it clear to a reader that the value is numeric even if they see only that one line; `if not x` does not. – Charles Duffy Nov 18 '15 at 22:05
  • if there is any chance that `x` will not be a float/int, ie if `x == Null or x == '' or x == []` etc. other than that, as @CharlesDuffy said, its just readability – R Nar Nov 18 '15 at 22:16
  • @RNar I think you mean `None`, not `Null` – Galax Nov 18 '15 at 22:33
  • @Galax yeeeeehhh, thats the one :P – R Nar Nov 18 '15 at 22:34
  • In MATLAB for an array of numbers, comparing with `0` has slightly upper hand. More info - [`Is A==0 really better than ~A?`](http://stackoverflow.com/questions/25339215/is-a-0-really-better-than-a). – Divakar Nov 21 '15 at 09:32

1 Answers1

2

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 '=='.

Proghero
  • 659
  • 1
  • 9
  • 20
  • Cool, I didn't know bytecode existed, but I guess that is what I wanted to know, which one takes less steps. – izxle Nov 18 '15 at 22:33
  • Yeah, you can always check the generated bytecode of a function using the ['dis' module](https://docs.python.org/3/library/dis.html). ;) – Proghero Nov 18 '15 at 22:38