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.

+3


source to share


5 answers


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.

+9


source


Try to use filter

for i in filter(lambda x: not x%2, l):
    print i

      



or simply list comprehension

>>>[i for i in l if not i%2]

      

+2


source


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

      

+1


source


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.

+1


source


Try the following:

filter(lambda x: x % 2 == 0, l)

      

-1


source







All Articles