Q:

How do you make long list comprehensions in python?

For example:
>>> [x for x in range(y) for y in range(z) for z in range(3)]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'y' is not defined

I would expect this to behave the same as:
>>> a=[]
>>> for z in range(3):
...   for y in range(z):
...     for x in range(3):
...       a.append(x)
... 
>>> a
[0, 1, 2, 0, 1, 2, 0, 1, 2]

But it doesn't. Why?

A:

Put the loop in the same order in which you would in traditional for loop:
>>> [x for z in range(3) for y in range(z) for x in range(3)]
[0, 1, 2, 0, 1, 2, 0, 1, 2]

A:

Your current comprehension will work if you reverse the order of the loops:
[x for z in range(3) for y in range(z) for x in range(3)]

A:

You can think of list comprehension this way:
[x for z in range(3)
       for y in range(z)
         for x in range(3) ]

Just remove the colons, wrap the for loops in brackets and have x at the front.

