8

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

2
  • 2
    It seems to me that the penalty of extra indentation in your last possibility is more than made up for by the increased clarity. Readability counts. Commented Mar 12, 2017 at 11:35
  • 1
    I think my second, non-working, example would be very readable. The last possibility is not bad, but I was just curious if something like the second was possible Commented Mar 12, 2017 at 15:52

2 Answers 2

5
  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.

Sign up to request clarification or add additional context in comments.

8 Comments

What's the point of map(b, (x for x in X if a(x))) if you're not going to actually run the generator? map(...) by itself is essentially a no-op. You need to either do list(map(...)) or for x in map(...):pass. (Unless we're talking about python 2, but in that case it's not true that "no unneeded list will be created")
b(x) is actually code of block ... will update my question
@Bananach You can wrap it in a function so it is actually b(x).
Yeah but the whole point of this question is to write pretty code, not workarounds
it is not a 100 line block of code. it is a 7 line block of code, that is used only at this occasion.
|
1

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.

4 Comments

@Elmex80s Yup, not the most efficient. Just depends on the use case. Sometimes it's worth sacrificing runtime for readability.
True, but with list comprehension you map and filter within one go.
@Elmex80s Yeah, personally, I don't have any issue with list comps, they're great; but for those not used to the language, it's another option. Of course, you could argue they should just make the leap and learn the list comp.
b(x) is actually a code of block ... will update my question

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.