I am learning python using the excellent book by Mark Lutz. I come across this statement that the ternary operator in python, which is effectively this:
if a: b else: c
can be written in 2 ways:
b if a else c: using normal ternary syntax of python and
((a and b) or c): using the equivalent but trickier
I find the second representation disconcerting as it doesn't go well with my instinct. I tried these 2 syntax on the interactive prompt and found different answers for special case of
b = 0. (assume b = 0, a = 4, c = 20)
0 if 4 else 20outputs
((4 and 0) or 20)outputs
It appears that the 2 expressions are equivalents for all the
truthy values of
b but are not equivalent for all the
falsy values of
I want to know, is there anything that I am missing here. Is my analysis wrong? Why does it say so in the book that the two cases are equivalent. Please enlighten my coarse mind. I am new to python. Thanks in advance.
You are right, the second approach is great in most cases.
From the python docs:
Before this syntax was introduced in Python 2.5, a common idiom was to use logical operators: [expression] and [on_true] or [on_false]
Right after that they mention:
"However, this idiom is unsafe, as it can give wrong results when on_true has a false boolean value. Therefore, it is always better to use the ... if ... else ... form.