I think I'm overlooking something simple, but I can't seem to figure out what exactly. Please consider the following code:
a = [2, 3, 4, 5]
lc = [ x for x in a if x >= 4 ] # List comprehension
lg = ( x for x in a if x >= 4 ) # Generator expression
a.extend([6,7,8,9])
for i in lc:
print("{} ".format(i), end="")
for i in lg:
print("{} ".format(i), end="")
I expected that both for-loops would produce the same result, so 4 5. However, the for-loop that prints the generator exp prints 4 5 6 7 8 9. I think it has something to do with the declaration of the list comprehension (Which is declared before the extend). But why is the result of the generator different, as it is also declared before extending the list? E.g. what is going on internally?