I tried to use the value of an outer list comprehension in an inner one:
[ x for x in range(y) for y in range(3) ]
But unfortunately this raises a NameError because the name y
is unknown (although the outer list comprehension specifies it).
Is this a limitation of Python (2.7.3 and 3.2.3 tried) or is there a good reason why this cannot work?
Are there plans to get rid of the limitation?
Are there workarounds (some different syntax maybe I didn't figure out) to achieve what I want?
Did you try:
Because that produces an output... This produces:
Which may or may not be what you wanted....
You are talking about list comprehensions, not generator expressions.
You need to swap your for loops:
You need to read these as if they were nested in a regular loop:
List comprehensions with multiple loops follow the same ordering. See the list comprehension documentation:
The same thing goes for generator expressions, of course, but these use
()
parenthesis instead of square brackets and are not immediately materialized:just nest another gen.
gives me: