Reputation: 10499
I have, in a function, a lot of consecutive statements like the following:
if condition1:
yield x
else:
yield None
if condition2:
yield y
else:
yield None
...
Is there a way to make more concise this kind of code?
Upvotes: 2
Views: 368
Reputation: 45552
Using conditional expressions would make it more concise:
yield x if condition1 else None
yield y if condition2 else None
Or if you have many (value, condition) pairs and don't mind evaluating all conditions up front:
for val, cond in [(x, condition1), (y, condition2)]:yield val if cond else None
Note: Second part of answer stricken for reasons given in comments below.
Upvotes: 4