implementing ternary operator in python using and/or combinations

3984 views python
1

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:

  1. b if a else c : using normal ternary syntax of python and

  2. ((a and b) or c) : using the equivalent but trickier and/or combination

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)

  1. 0 if 4 else 20 outputs 0
  2. ((4 and 0) or 20) outputs 20

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 b.

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.

answered question

No, you seem to have gotten it right. It must be the book you are reading, that is a bit vauge on when the second way is equal to the first.

1 Answer

13

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.

Here's a reference: https://docs.python.org/3.3/faq/programming.html#is-there-an-equivalent-of-c-s-ternary-operator

posted this

Have an answer?

JD

Please login first before posting an answer.