List comprehension in python


#1



https://www.codecademy.com/courses/python-beginner-en-KAgt5/1/2?curriculum_id=4f89dab3d788890003000096#


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

#2

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

:


#3

thanks I forgot about the list part