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

Python

Python Problem Overview


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?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

You could do:

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

Solution 3 - Python

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>

Solution 4 - Python

Mabe this, but it's more or less the same verbose...

import itertools

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

Solution 5 - Python

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.

Solution 6 - Python

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).

Solution 7 - Python

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)))

Solution 8 - Python

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

for airport in [a for a in airports if a.is_important]:

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionTal WeissView Question on Stackoverflow
Solution 1 - Pythone-satisView Answer on Stackoverflow
Solution 2 - PythonChristopheDView Answer on Stackoverflow
Solution 3 - Pythonuser97370View Answer on Stackoverflow
Solution 4 - PythonfortranView Answer on Stackoverflow
Solution 5 - PythonShane HollowayView Answer on Stackoverflow
Solution 6 - PythonShawnFumoView Answer on Stackoverflow
Solution 7 - Pythonabhisheksr01View Answer on Stackoverflow
Solution 8 - PythonrogeriopvlView Answer on Stackoverflow