Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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?

like image 803
Tal Weiss Avatar asked Mar 08 '10 14:03

Tal Weiss


People also ask

How do you combine for loop and if condition in Python?

Combine for loop and nested-if statements in Python If you want to combine a for loop with multiple conditions, then you have to use for loop with multiple if statements to check the conditions. If all the conditions are True, then the iterator is returned.

How do you filter a for loop?

You can use . filter() for that. The way filter works is you loop over every single item in an array, and you either say yes (true) or no (false). If you return true that item will be in the array subset, if you return false it will take out that item from the array that is returned.

Can you put a for loop in an if statement in Python?

Inside a for loop, you can use if statements as well.


1 Answers

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.

like image 70
e-satis Avatar answered Sep 20 '22 21:09

e-satis