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

202
Visualizações
Why does redefining a variable used in a generator give strange results?

One of my friends asked me about this piece of code:

array = [1, 8, 15]
gen = (x for x in array if array.count(x) > 0)
array = [2, 8, 22]
print(list(gen))

The output:

[8]

Where did the other elements go?

over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

The answer is in the PEP of the generator expressions, in particular the session Early Binding vs Late biding:

After much discussion, it was decided that the first (outermost) for-expression should be evaluated immediately and that the remaining expressions be evaluated when the generator is executed.

So basically the array in:

x for x in array 

is evaluated using the original list [1, 8, 15] (i.e. immediately), while the other one:

if array.count(x) > 0

is evaluated when the generator is executed using:

print(list(gen))

at which point array refers to a new list [2, 8, 22]

over 4 years ago · Santiago Trujillo Relatório

0

This becomes more clear if you give each array a unique name instead of re-binding array:

array1 = [1, 8, 15]
gen = (x for x in array1 if array2.count(x) > 0)
array2 = [2, 8, 22]
print(list(gen))

x for x in array1 is evaluated at creation of the generator, but if array2.count(x) > 0 is evaluated lazily, which is why you can already reference a yet undefined variable

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