-1

I know there're some other articles talk about how to simulate ternary operator in Python, but my question here is not how can I simulate it, but why do these ways work.

As we all know simulating a ternary operator (condition: if_true ? if_false) is done by

a if condition else b

However, there're at least two other ways to accomplish that, e.g.

(if_false, if_true)[test]

and

(expression) and (if_true) or (if_false)

Example would be

(4, 5)[4 > 5]

gives 4

4 > 5 and 4 or 5

gives 5

Stephen Fong
  • 697
  • 5
  • 17
  • There is extensive explanation of various ternary operator alternatives in [Does Python have a ternary conditional operator?](https://stackoverflow.com/questions/394809/does-python-have-a-ternary-conditional-operator) – khelwood May 16 '19 at 15:03
  • @khelwood That question is not duplicate as I'm asking why do two other ways work, whereas the link you posted only tells what are the ways. – Stephen Fong May 16 '19 at 15:13

1 Answers1

4

That's because boolean in python is a subclass of int. And True is 1 while False is 0. And that is being used as an index into the tuple. So,

(4, 5)[4 > 5]
>>> (4, 5)[False]
>>> (4, 5)[0]
>>> 4

Your second method is a bit more hard-to-read:

4 > 5 and 4 or 5
>>> ((4 > 5) and 4) or 5
>>> (False and 4) or 5
>>> False or 5
>>> 5

This one relies on the fact that and and or on truth-y or false-y values, yield the value and not a boolean.

rdas
  • 20,604
  • 6
  • 33
  • 46
  • 2
    There's some subtlety that might be initially confusing to some (it was for me). The result of the comparison is being used as an accessor. `4 > 5` evaluates to False, which as you've pointed out equals 0 and then we access the 0th element of the tuple `(4, 5)` – zerocool May 16 '19 at 15:12