For singular if
, the syntax is:
[print("YAY") for c,v in zip(conditions,values) if c==v]
This translates to:
for c,v in zip(conditions,values):
if c==v:
print('YAY')
For multiple if
and elif
and else
, the syntax is:
[print("YAY") if c==v else print("lalala") if c=='some other condition' else print("NAY") for c,v in zip(conditions,values)]
This translates to
for c,v in zip(conditions,values):
if c==v:
print('YAY')
elif c=='some other condition':
print('lalala')
else:
print('NAY')
We can test this:
conditions = [1, 2, 3, 4, 'some other condition']
values = [1, 2, 3, 3, 999]
[print("YAY") if c==v else print("lalala") if c=='some other condition' else print("NAY") for c,v in zip(conditions,values)]
#YAY
#YAY
#YAY
#NAY
#lalala
EDIT: If you want to handle nested for
loops in list comprehension, note that the following code are equivalent:
newlist = []
for c in conditions:
for v in values:
newlist.append((c,v))
print (newlist)
# [(1, 1), (1, 2), (1, 3), (1, 3), (1, 999), (2, 1), (2, 2), (2, 3), (2, 3), (2, 999), (3, 1), (3, 2), (3, 3), (3, 3), (3, 999), (4, 1), (4, 2), (4, 3), (4, 3), (4, 999), ('some other condition', 1), ('some other condition', 2), ('some other condition', 3), ('some other condition', 3), ('some other condition', 999)]
and
newlist = [(c,v) for c in conditions for v in values]
print (newlist)
#[(1, 1), (1, 2), (1, 3), (1, 3), (1, 999), (2, 1), (2, 2), (2, 3), (2, 3), (2, 999), (3, 1), (3, 2), (3, 3), (3, 3), (3, 999), (4, 1), (4, 2), (4, 3), (4, 3), (4, 999), ('some other condition', 1), ('some other condition', 2), ('some other condition', 3), ('some other condition', 3), ('some other condition', 999)]
Note that for c in conditions
is the outer loop and for v in values
is the inner loop for both snippets of code