If-for-else nested set comprehension in python

149 views Asked by At

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.

3

There are 3 answers

4
oskros On BEST ANSWER

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}
0
Ade_1 On

try this

proceed={x for x in statements} if isinstance(statements, list) else statements 
0
Daweo On

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)