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

264
Visualizações
Efficiently filtering out 'None' items in a list comprehension in which a function is called

I have a list comprehension that calls a function which potentially returns None.

>>> f = lambda x: x if x < 3 else None
>>> l = [f(x) for x in [1,2,3,4]]
[1, 2, None, None]

I'd like to have the list comprehension as above, without the 'None' entries.

What's a more efficient way to do the following, without creating additional overhead, and while retaining the efficiency of the list comprehension?

>>> filter(None, [f(x) for x in [1,2,3,4]])
[1, 2]
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Add an if into your comprehension like:

l = [y for y in (f(x) for x in [1,2,3,4]) if y is not None]

By placing a Generator Expression inside the list comprehension you will only need to evaluate the function once. In addition the generator expression is a generator so takes no extra intermediate storage.

Python 3.8+

As of Python 3.8 you can use an Assignment Expression (:=) (AKA: Named Expressions or the Walrus Operator) to avoid multiple evaluations of f() like:

l = [y for x in [1,2,3,4] if (y := f(x)) is not None]
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