Search code examples
pythonfor-loopgeneratorone-liner

I am trying to get the one line generator expression to do nothing if the condition is not True


Here is my code, I was trying to subtract two lists using a generator expression but I couldn't get the generator expression to do nothing is if the condition is not met.

ab=[1,2,2,3,4,5]
b=[3,4,5]
[ a if a in list(set(ab)-set(b)) else (nothing) for a in ab]

I want the generator expression to return [1,2,2]


Solution

  • I think you want this (list of items in ab that are not in b)

    [x for x in ab if x not in b]