[Python-ideas] More power in list comprehensions with the 'as' keyword

Leif Walsh leif.walsh at gmail.com
Fri Aug 29 03:16:20 CEST 2008

-1 on the first post.

> [l.strip() as stripped for l in text.split('\n') if stripped != '']

This is equivalent, with respect to semantics as well as efficiency, to:

[s for s in (l.strip() for l in text.split('\n')) if s != '']

And, even easier to read:

stripped = (l.strip() for l in text.split('\n'))
non_null_lines = [s for s in stripped if s]  # let's use the implicit
truth value too

It seems to me that there's too much being asked for here when the
tools are already all available.  Generator expressions/list
comprehensions seem to be getting a lot of attention from python-ideas
lately, when it's really making the code _harder_ to read, and not
even easier to write, because of all the extra thinking required.  In
fact, most of these things are better done with straight-out looping
and yielding:

for line in text.split('\n'):
  stripped = l.strip()
  if stripped:
    yield stripped

Now _that_ I can read!


More information about the Python-ideas mailing list