Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Python have the Elvis operator?

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
like image 856
Cory Klein Avatar asked Feb 15 '18 17:02

Cory Klein


People also ask

Does Python have the ternary operator?

The ternary operator is a way of writing conditional statements in Python. As the name ternary suggests, this Python operator consists of three operands. The ternary operator can be thought of as a simplified, one-line version of the if-else statement to test a condition.

Does Python have the operator?

Operators are special symbols in Python that carry out arithmetic or logical computation. The value that the operator operates on is called the operand. Here, + is the operator that performs addition.

Does Python have conditional operator?

Python supports one additional decision-making entity called a conditional expression. (It is also referred to as a conditional operator or ternary operator in various places in the Python documentation.) Conditional expressions were proposed for addition to the language in PEP 308 and green-lighted by Guido in 2005.

Why is it called the Elvis operator?

A : B . The name "Elvis operator" refers to the fact that when its common notation, ?: , is viewed sideways, it resembles an emoticon of Elvis Presley with his signature hairstyle.


1 Answers

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

like image 61
Robᵩ Avatar answered Sep 30 '22 19:09

Robᵩ