Reputation: 33
I have this code:
result = []
for x in [10, 20, 30]:
for y in [2, 3, 4]:
if y > 0:
result.append(x ** y)
result
[100, 1000, 10000, 400, 8000, 160000, 900, 27000, 810000]
I'm trying to convert it to list comprehension with no luck(new in python)
This is my attempt:
print [ x ** y if y > 0 for x in [10, 20, 30] for y in [2, 3, 4]]
But there is a problem in the statement, any help will be most appropriated.
error:
File "<stdin>", line 1
print [ x ** y if y > 0 for x in [10, 20, 30] for y in [2, 3, 4]]
^
SyntaxError: invalid syntax
Upvotes: 3
Views: 108
Reputation: 155
Remember this Syntax for Comprehension. '{}' for dict comprehension
[ expression for target1 in iterable1 if condition1
for target2 in iterable2 if condition2 ...
for targetN in iterableN if conditionN ]
Upvotes: 1
Reputation: 239453
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]
Upvotes: 7
Reputation: 53678
You need the if statement at the end of the list comprehension
print [ x ** y for x in [10, 20, 30] for y in [2, 3, 4] if y > 0]
Upvotes: 6