Reputation: 632
Suppose the below variables:
xs = [1,2]
ys = ['a','b']
I also have 2 for loops and an if condition like below:
zs = []
for x in xs:
for y in ys:
if x == 2:
zs.append(x * y)
else:
zs.append(y * 3)
and the output is like below:
['aaa', 'bbb', 'aa', 'bb']
how can I achieve this with list comprehension? I have tried the below code, which is an invalid syntax:
zs = [(x * y) for x in xs for y in ys if x == 2 else y * 3]
As far as I know, in list comprehension, the first for corresponds to outer loop and the second loop corresponds to inner loop.
If I provide the "If condition" before the "for loop", it means that the code first checks the condition and then the for loops and if I provide the "for loops" first and then the "If condition", it means that first the for loops run and within the inner for loop, the "If condition" validates. Is that right?
I hope I could articulate my problem.
Upvotes: 0
Views: 72
Reputation: 3196
You should use the following list comprehension:
zs = [(x * y) if x == 2 else (y * 3) for x in xs for y in ys]
Result:
['aaa', 'bbb', 'aa', 'bb']
Upvotes: 2