I'm curious which form is more efficient, is correct style, etc. I feel like the ".0" approach is much quicker; I'm not sure why the "float" approach is equally appreciated (if it is).
Using float(7)
adds some unnecessary overhead—Python has to find the float
function in globals()
and call it. Using 7.0
does all the necessary conversions at compile-time instead of run-time. You can see this using the Python bytecode disassembler.
>>> import dis
>>> def f(): return 7.0
...
>>> def g(): return float(7)
...
>>> dis.dis(f)
1 0 LOAD_CONST 1 (7.0)
3 RETURN_VALUE
>>> dis.dis(g)
1 0 LOAD_GLOBAL 0 (float)
3 LOAD_CONST 1 (7)
6 CALL_FUNCTION 1
9 RETURN_VALUE
use the 7.0
approach, the float(7)
approach is used to transform integer or string types to floats so it's a different use, for example:
a = 7
b = "7"
print float(a)
7.0
print float(b)
7.0
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With