charrison
charrison

Reputation: 857

Python: using comprehensions in for loops

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.

Upvotes: 3

Views: 133

Answers (5)

Mahi
Mahi

Reputation: 21883

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.

Upvotes: 9

Sandip Sinha
Sandip Sinha

Reputation: 1

Try this:

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

Upvotes: -1

skyking
skyking

Reputation: 14390

No. The for statement requires that what comes after in is an expression list that evaluates to an iterable object (one that has an __iter__) method.

The compact alternatives are to use either a generator or a list comprehension (list having the downside that the list has to be built before the for loop starts - giving in effect two loops). You have to select one of the alternatives the language provides.

Upvotes: 1

itzMEonTV
itzMEonTV

Reputation: 20339

Try this using 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]

Upvotes: 2

Aditya
Aditya

Reputation: 3158

Can't make it work that way. However here are other pythonic styles:

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 a list defined by [x for x in l if x%2==0]

Well, you could always use the vanilla approach:

for e in l:
    if e % 2 == 0:
        print e

Upvotes: 1

Related Questions