List comprehension in python


even_squares = [x**2 for x in range(1,12) if (x**2) % 2 ==0]

print even_squares

I'm having a little trouble understanding this syntax. Would the following code be equivalent

for x in range(1,12):
    x = x ** 2
    if x % 2 == 0:
        print x


It's nearly equivalent except the first example builds a list, then prints the whole object. The second example prints each value directly as it is computed.

There is a flaw in the second example, though... x is initialized as the iterator in the for statement. It should not be re-used (re-assigned) in the block else things go all wonky.

    if x % 2 == 0:
        print x ** 2

A near equivalent to the first example would be something like,

y = []
for x in range(1,12):
    if x % 2 == 0:
        y.append(x ** 2) 
print y



thanks I forgot about the list part