Single line for loop over iterator with an "if" filter?

Question:

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?

Asked By: Tal Weiss

||

Answers:

Mabe this, but it’s more or less the same verbose…

import itertools

for airport in itertools.ifilter(lambda x: x.is_important, airports):
    ...
Answered By: fortran

You could do:

for airport in filter(lambda x: x.is_important, airports):
    # do stuff...
Answered By: ChristopheD

Using list comprehension (only if airports is a list of objects):

for airport in [a for a in airports if a.is_important]:
Answered By: rogeriopvl

This is a design philosophy of python. If it takes you too many words to put it on one line, it should be broken into a few lines to help the person who comes after you. List and generator expressions are more for transforming iterables in-place — making more readable forms of map and filter.

Answered By: Shane Holloway

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.

Answered By: e-satis

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>
Answered By: user97370

Here’s an alternative to some of the other filter versions:

from operator import attrgetter as attr
for airport in filter(attr('is_important'), airports):
    ...

This has the advantages of being pretty concise and also letting you use dot notation attr(‘first_class.is_full’).

You could also put something like that (or a version using a list comprehension) into a utility function like filter_by_attr. Then you could do:

for airport in filter_by_attr(airports, 'is_important'):
    ...

I still think e-satis is right to put it in a new variable no matter the method you use, though. It is just clearer that way, especially if the use doesn’t exactly match the name of the attribute in question (or the the criteria is more complex).

My only note on that would be that if you find yourself using this in several places, perhaps you should make airports a special collection with ‘important_airports’ being a @property which returns the filtered collection. Or some sort other abstraction to hide away the filtering (like a service call).

Answered By: ShawnFumo

I found the usage of the filter & lambda to be the easiest in a single line.

for filtered_airport in filter(lambda airport: airport.is_important, airports)):
    print(filtered_airport.some_property)

If you wish to return a list from output of this filter object you can do something like this.

filtered_airport_list = list(filter(lambda airport: airport.is_important, airports)))
Answered By: abhisheksr01
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.