An alternate form of the Python ternary operator

I recently discovered an alternative to the standard construction of " expression_on_true if predicate else expression_on_false ", which I have not seen in directories:

(expression_on_false, expression_on_true)[predicate]

image

How it works


  1. In parentheses, a tuple of two elements is declared.
  2. In square brackets, the predicate value is calculated.
  3. A tuple is accessed at index 1 (if the value of the predicate is True) or 0 (if the value of the predicate is False)

Let's look at an example


Suppose we have a , and we need to print โ€œpositiveโ€ if the number is not less than zero, or โ€œnagativeโ€ if the number is less than zero.


>>> a = 101
>>> ("negative", "positive")[a >= 0]
'positive'
>>> a = -42
>>> ("negative", "positive")[a >= 0]
'negative'
>>> a = 0
>>> ("negative", "positive")[a >= 0]
'positive'

In the first case, 101> = 0, so the predicate returns True. When indexing, True turns to 1, so the call goes to the element with index 1. In the second case, the same: the predicate is False, the call goes to the element with index 0.

Construction ("negative", "positive") [a> = 0] at least and not much shorter than "positive" if a> = 0 else "positive" , but I still find this feature interesting

Note


(thanks to Dasdy )
If instead of constants we substitute expressions into the tuple, of which only one should be executed, then this construction loses its meaning.

All Articles