The ternary operator in many languages works like so:
x = f() ? f() : g()
Where if f()
is truthy then x
is assigned the value of f()
, otherwise it is assigned the value of g()
. However, some languages have a more succinct elvis operator that is functionally equivalent:
x = f() ?: g()
In python, the ternary operator is expressed like so:
x = f() if f() else g()
But does python have the more succinct elvis operator?
Maybe something like:
x = f() else g() # Not actually valid python
Python does have the elvis operator. It is the conditional or
operator:
x = f() or g()
f()
is evaluated. If truthy, then x is assigned the value of f()
, else x is assigned the value of g()
.
Reference: https://en.wikipedia.org/wiki/Elvis_operator#Analogous_use_of_the_short-circuiting_OR_operator