Note: It's true that this question has been answered for many other languages. However, I could not find an answer for Python, so do not mark as duplicate.
Is there a difference in performance between the if-else statement and the ternary operator in Python?
I doubt there is a performance difference. They compile to equivalent sequences of bytecodes:
>>> def f():
... return a if b else c
...
>>> dis.dis(f)
2 0 LOAD_GLOBAL 0 (b)
2 POP_JUMP_IF_FALSE 8
4 LOAD_GLOBAL 1 (a)
6 RETURN_VALUE
>> 8 LOAD_GLOBAL 2 (c)
10 RETURN_VALUE
>>> def g():
... if b:
... return a
... else:
... return c
...
>>> dis.dis(g)
2 0 LOAD_GLOBAL 0 (b)
2 POP_JUMP_IF_FALSE 8
3 4 LOAD_GLOBAL 1 (a)
6 RETURN_VALUE
5 >> 8 LOAD_GLOBAL 2 (c)
10 RETURN_VALUE
12 LOAD_CONST 0 (None)
14 RETURN_VALUE
As with most performance questions, the answer is to measure.
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