Python: Using Concepts for Loops
I am 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 state. Here's an illustration of what I would like to do:
l = [1, 2, 3, 4, 5, 6]
for e in l if e % 2 == 0:
print e
which strikes me as very neat and Pythonic, and fine in every way except for a little syntax error question. This alternative works:
for e in (e for e in l if e % 2 == 0):
print e
but is ugly like sin. Is there a way to add a condition directly to the construction of the loop without creating a generator?
Edit: You might assume that the processing and filtering that I actually want to do on e
is more complex than the example above. Processing in particular does not apply to a single line.
source to share
What's wrong with a simple, straightforward solution:
l = [1, 2, 3, 4, 5, 6]
for e in l:
if e % 2 == 0:
print e
You can have any number of statements instead of a simple one print e
, and no one should scratch their heads trying to figure out what they are doing.
If you need to use an additional list for something else (and not just iterate over it once), why not build a new list instead:
l = [1, 2, 3, 4, 5, 6]
even_nums = [num for num in l if num % 2 == 0]
And now let's move on to even_nums
. Another line, more readable.
source to share
There is no way to get this to work. However, there are other pythonic styles here:
print [ e for e in l if e%2==0 ]
If you want to stick to your style, use this list comprehension:
for e in [x for x in l if x%2==0]:
print e
So here e is iterating over the list defined [x for x in l if x%2==0]
Well, you can always use the vanilla approach:
for e in l:
if e % 2 == 0:
print e
source to share
Not. The operator for
requires that what comes after in
is a list of expressions that evaluates the iterable object (method __iter__
).
Compact alternatives are to use a generator or a list comprehension (the list has the disadvantage that it has to be created to create the list before the for loop, which gives two loops). You must choose one of the options provided by the language.
source to share