16

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
Cory Klein
  • 40,647
  • 27
  • 164
  • 222

3 Answers3

36

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

Jerry Jeremiah
  • 7,408
  • 2
  • 21
  • 27
Robᵩ
  • 143,876
  • 16
  • 205
  • 276
3

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

Aleksandr Dubinsky
  • 19,357
  • 14
  • 64
  • 88
  • OP specifically asked about checking `a` for truthiness, not checking `a is not None`. – CrazyChucky Dec 27 '20 at 16:50
  • 1
    @CrazyChucky Hmm, I may have fudged the distinction between the elvis operator and the null-coalescing operator. Nevertheless I'll leave this answer up for others who may have the same confusion. – Aleksandr Dubinsky Dec 27 '20 at 17:23
  • Good point, I think it's worth pointing out. Perhaps mention specifically that the Elvis and null-coalescing operator are similar, but have this distinction? – CrazyChucky Dec 27 '20 at 17:25
  • 1
    @CrazyChucky Edited. I'll point out that some languages, like Kotlin, use `?:` for null-coallescing and Wikipedia actually has sections for both behaviors under ["elvis operator"](https://en.wikipedia.org/wiki/Elvis_operator#Object_reference_variant) and in examples has entries for '??' as well. So the term is not exactly clear-cut. – Aleksandr Dubinsky Dec 27 '20 at 17:36
-3
>>> 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
Blessed Geek
  • 19,240
  • 21
  • 96
  • 165