Reputation: 601
I'm trying to convert the following nested conditions to set comprehension, but couldn't get it working properly.
processed = set()
if isinstance(statements, list):
for action in statements:
processed.add(action)
else:
processed.add(statements)
I tried the following but looks I'm making a mistake
processed = {action for action in statements if isinstance(statements, list) else statements}
Edit: Where statements
can be a list or string.
Upvotes: 0
Views: 150
Reputation: 36360
If you do not have to use set-comprehension AT ANY PRICE then your code might be simplified by using .update
method of set
, which accept iterable and has same effect as using .add
for each element of iterable. Simplified code:
processed = set()
if isinstance(statements, list):
processed.update(statements)
else:
processed.add(statements)
Upvotes: 0
Reputation: 3285
You need the if
statement outside the set comprehension, as in the else
case, statements
is not an iterable
processed = {action for action in statements} if isinstance(statements, list) else {statements}
Upvotes: 3
Reputation: 1486
try this
proceed={x for x in statements} if isinstance(statements, list) else statements
Upvotes: 1