-2

After working through some toy examples, I could see that it's possible to emulate the ternary operator of "c" condition?value_if_true:value_if_false in Python using condition and value_if_true or value_if_false. I would like to know if it works in all cases and if it is better or worse than using value_if_true if condition else value_if_false.

  • 1
    Personally, the *precedence* of `.. if .. else ..` is clear. I'd at least have to think twice about an `.. and .. or ..`. – deceze Jul 27 '22 at 12:58
  • Why wasn't `condition and value_if_true or value_if_false` nuked from orbit in Python 3? I can't unsee this! – Panagiotis Kanavos Jul 27 '22 at 13:00
  • @PanagiotisKanavos There's nothing wrong with the expression itself, only assuming that `X and Y or Z` will also evaluate to `Y` when `X` is true. – chepner Jul 27 '22 at 13:07

1 Answers1

3

It's strictly worse: the conditional expression was added to the language specifically to avoid the problem with using ... and ... or ... incorrectly.

# 0 is falsy
>>> True and 0 or 5
5
>>> 0 if True else 5
0

PEP-308 references "FAQ 4.16" for other workarounds to the problems with and/or, though I can no longer track down what FAQ is being referred to, but it was eventually decided that a dedicated conditional expression was preferable.

For example, one could write

(True and [0] or [3])[0]

to ensure that the true-result is truthy, so that the false-result isn't returned. The false-result has to be adjusted as well so that regardless of what result is produced, it can be indexed to finally provide the intended result.

chepner
  • 497,756
  • 71
  • 530
  • 681