Single line for loop over iterator with an "if" filter?
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?
No, there is no shorter way. Usually, you will even break it into two lines :
important_airports = (airport for airport in airports if airport.is_important)
for airport in important_airports:
# do stuff
This is more flexible, easier to read and still don't consume much memory.
You could do:
for airport in filter(lambda x: x.is_important, airports):
# do stuff...
I'd use a negative guard on the loop. It's readable, and doesn't introduce an extra level of indentation.
for airport in airports:
if not airport.is_important: continue
<body of loop>
Mabe this, but it's more or less the same verbose...
import itertools
for airport in itertools.ifilter(lambda x: x.is_important, airports):
...