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?
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.
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.
Inside a for loop, you can use if statements as well.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With