Prakash
Prakash

Reputation: 601

If-for-else nested set comprehension in python

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

Answers (3)

Daweo
Daweo

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

oskros
oskros

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

Ade_1
Ade_1

Reputation: 1486

try this

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

Upvotes: 1

Related Questions