[x for x in temp1 if x not in s]
It may help to re-order it slightly, so you can read the whole thing left to right. Let's move the first x
to the end.
[for x in temp1 if x not in s yield x]
I've added a fake yield
keyword so it reads naturally as English. If we then add some colons it becomes even clearer.
[for x in temp1: if x not in s: yield x]
Really, this is the order that things get evaluated in. The x
variable comes from the for
loop, that's why you can refer to it in the if
and yield
clauses. But the way list comprehensions are written is to put the value being yielding at the front. So you end up using a variable name that's not yet defined.
In fact, this final rewrite is exactly how you'd write an explicit generator function.
def func(temp1, s):
for x in temp1:
if x not in s:
yield x
If you call func(temp1, s)
you get a generator equivalent to the list. You could turn it into that list with list(func(temp1, s))
.