Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

686
Visualizações
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
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

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

over 4 years ago · Santiago Trujillo Relatório

0

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

over 4 years ago · Santiago Trujillo Relatório

0

Robᵩ's answer about using or is a good suggestion. However, as a comment to the original question,

x = f() ? f() : g()

is functionally equivalent with

x = f() ?: g()

only if f() has no side effects.

If, for instance, f() reads from a stream or generator, calling it twice will have different results than calling it once. Rewriting slightly to Python syntax, the following sample

values = (x for x in (1, 2, 3))
def f(): return next(values)
def g(): return 42
x = f() if f() else g()
print(x)

will print 2, while x = f() or g() would print 1.

It might be better to state the question as

tmp = f()
x = tmp ? tmp : g()

or, in Python,

tmp = f()
x = tmp if tmp else g()

or in Python 3.8 and up,

x = tmp if (tmp := f()) else g()

Both of the latter two examples are equivalent with

x = f() or g()

regardless of any side effects f() might have.

over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda