I'm using Python 2.7. I have a list, and I want to use a for loop to iterate over a subset of that list subject to some condition. Here's an illustration of what I'd like to do:
l = [1, 2, 3, 4, 5, 6]
for e in l if e % 2 == 0:
print e
which seems to me very neat and Pythonic, and is lovely in every way except for the small matter of a syntax error. This alternative works:
for e in (e for e in l if e % 2 == 0):
print e
but is ugly as sin. Is there a way to add the conditional directly to the for loop construction, without building the generator?
Edit: you can assume that the processing and filtering that I actually want to perform on e are more complex than in the example above. The processing especially doesn't belong one line.
What's wrong with a simple, readable solution:
l = [1, 2, 3, 4, 5, 6]
for e in l:
if e % 2 == 0:
print e
You can have any amount of statements instead of just a simple print e and nobody has to scratch their head trying to figure out what it does.
If you need to use the sub list for something else too (not just iterate over it once), why not construct a new list instead:
l = [1, 2, 3, 4, 5, 6]
even_nums = [num for num in l if num % 2 == 0]
And now iterate over even_nums. One more line, much more readable.
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