The filtering condition has to be at the end, like this
print [x ** y for x in [10, 20, 30] for y in [2, 3, 4] if y > 0]
because the grammar for list comprehension is defined like this
list_display ::= "[" [expression_list | list_comprehension] "]"
list_comprehension ::= expression list_for
list_for ::= "for" target_list "in" old_expression_list [list_iter]
list_iter ::= list_for | list_if
list_if ::= "if" old_expression [list_iter]
So only expressions can come before the for..in
and if
statement can come only after that.
In your case, expression
is satisfied by x ** y
and then list_for
is satisfied by for x in [10, 20, 30]
and then another list_for
is satisfied by for x in [10, 20, 30]
and finally the list_if
is satisfied by if y > 0
. It is of the form
[ expression list_for list_for list_if ]
BTW, you can do the same with itertools.product
, like this
from itertools import product
print [num**power for num,power in product([10, 20, 30], [2, 3, 4]) if power > 0]