Pythonic way to combine FOR loop and IF statement

ChewyChunks picture ChewyChunks · Aug 8, 2011 · Viewed 423.8k times · Source

I know how to use both for loops and if statements on separate lines, such as:

>>> a = [2,3,4,5,6,7,8,9,0]
... xyz = [0,12,4,6,242,7,9]
... for x in xyz:
...     if x in a:
...         print(x)
0,4,6,7,9

And I know I can use a list comprehension to combine these when the statements are simple, such as:

print([x for x in xyz if x in a])

But what I can't find is a good example anywhere (to copy and learn from) demonstrating a complex set of commands (not just "print x") that occur following a combination of a for loop and some if statements. Something that I would expect looks like:

for x in xyz if x not in a:
    print(x...)

Is this just not the way python is supposed to work?

Answer

Kugel picture Kugel · Aug 8, 2011

You can use generator expressions like this:

gen = (x for x in xyz if x not in a)

for x in gen:
    print x