Bananach
Bananach

Reputation: 2311

Python: For loop over list comprehension

Is there a shorter way to write

for x in [x for x in X if a(x)]:
    <Do something complicated with x>

Unfortunately, the following does not work:

for x in X if a(x):
    <Do something complicated with x>

Of course, I could achieve the desired result by

for x in X:
    if a(x):
        <Do something complicated with x>

but this would introduce an extra level of indentation

Upvotes: 7

Views: 2856

Answers (2)

Benjamin Rowell
Benjamin Rowell

Reputation: 1411

Not everyone is a fan of the following, but I quite like the map and filter funcs for readability...

list(map(b, filter(a, X))

It will achieve what you want, and I think it's easier to see what's going on.

Upvotes: 1

DeepSpace
DeepSpace

Reputation: 81594

  1. [b(x) for x in X if a(x)] is the simplest but will create an unnecessary list.

  2. map(b, (x for x in X if a(x))) will use a generator so no unneeded list will be created.

Upvotes: 5

Related Questions