18
votes

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
3
Undoing the dupe-close because this is not asking for null-coalescing behavior. (Also, the accepted answer on the old dupe target is bug-prone and terrible.) - user2357112 supports Monica

3 Answers

38
votes

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

4
votes

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

-3
votes
>>> a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4]
>>> a + (b,c)[b>c]
[1, 2, 3, 4]
>>> a + (b,c)[b<c]
[1, 2, 3, 4, 5, 6]
>>> 

Python elvis operation is

(testIsFalse, testIsTrue)[test]

The Java equivalent is

test ? testIsTrue:testIsFalse