pythonpython-3.xlist-comprehensionset-comprehension

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.


Solution

  • 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}