Why does redefining a variable used in a generator give strange results? [duplicate]

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]

Leave a Comment

tech