Python 3 if else one line or ternary operator
Ternary conditional operator or know also as one line if else is available in Python and can be best explain by following examples:
- condition ? value_if_true : value_if_false
- as expression:
a ? b : c
In this post:
- Ternary operator in Python
- Misleading ternary operator
- Performance test
- Check your code for ternary operators if any
Note that Python has also Elvis operator equivalent: x = a or b
- evaluate a if true then is assigned to x else assigned the value of b
Ternary operator in Python
The python syntax is a bit different from the other languages and it is:
value_if_true if condition else value_if_false
Example with true and false
'true' if True else 'false'
'true' if False else 'false'
other examples
'not x' if val != 'x' else 'x'
'x' if val == 'x' else 'not x'
Some points to consider about Ternary operator or one line if else:
- from performance point of view there isn't difference to normal if else (check section Performance test)
- the order of elements is different from traditional accepted structure which can be misleading for people with different background from python
- debug of classic if else is easier
- the syntax could be misleading (check section Misleading ternary operator)
Misleading ternary operator
If you think that you understand everything about ternary operator then try to predict the output of the following code examples. I needed 5 minutes until I really understand what is happening here:
x=1
y=0
z = 1 + x if x < y else y
print (z)
z = 1 + (x if x < y else y)
print (z)
x=2
y=1
z = 1 + x if x < y else y
print (z)
z = 1 + (x if x < y else y)
print (z)
result:
0
1
1
2
In fact the value of z is equal to the result of the ternary operator in the first example while the second(with the parenthesis) you get an expected result - sum 1 and the result of the ternary operator.
Performance test
Testing the performance of the if else and ternary operator gives a similar results. You can find the profiling results and code below:
import pickle
import cProfile
def before():
for i in range(1, 100000000):
3 if True else 8
def after():
for i in range (1, 100000000):
if False:
3
else:
8
cProfile.run('before()')
cProfile.run('after()')
4 function calls in 2.543 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 2.543 2.543 <string>:1(<module>)
1 2.543 2.543 2.543 2.543 ProfilingIsolation.py:4(before)
1 0.000 0.000 2.543 2.543 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
4 function calls in 2.091 seconds
Ordered by: standard name
ncalls tottime percall cumtime percall filename:lineno(function)
1 0.000 0.000 2.091 2.091 <string>:1(<module>)
1 2.091 2.091 2.091 2.091 ProfilingIsolation.py:9(after)
1 0.000 0.000 2.091 2.091 {built-in method builtins.exec}
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Check your code for ternary operators if any
You can use PyCharm and regular expression search in order to find if there are any ternary operators in your code. This is what you need to do:
- Find in Path ( CTRL+SHIFT+F
- Enter search text -
.* if .* else .*
- Check Regex