In Python, can I single line a for loop over iterator with an IF filter?

Posted by Tal Weiss on Stack Overflow See other posts from Stack Overflow or by Tal Weiss
Published on 2010-03-08T14:03:33Z Indexed on 2010/03/08 14:06 UTC
Read the original article Hit count: 261

Filed under:

Silly question:
I have a simple for loop followed by a simple if statement:

for airport in airports:
    if airport.is_important:

and I was wondering if I can write this as a single line somehow.
So, yes, I can do this:

for airport in (airport for airport in airports if airport.is_important):

but it reads so silly and redundant ("for airport in airport for airport in airports...").
Is there a better way?

© Stack Overflow or respective owner

Related posts about python