Does Python have the Elvis operator?
Yes
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
NB Python does not have the null-coalescing operator defined by:
a if a is not None else b
The or
operator in a or b
checks the truthiness of a
which is False
when a==0
or len(a)==0
or other similar situations. See What is Truthy and Falsy
There is a proposal to add such operators PEP 505