Half-baked idea: list comprehensions with "while"

Ian Kelly ian.g.kelly at gmail.com
Thu Apr 26 13:11:49 EDT 2012


On Thu, Apr 26, 2012 at 11:02 AM, Roy Smith <roy at panix.com> wrote:
> I'm not seriously suggesting this as a language addition, just an interesting idea to simplify some code I'm writing now:
>
> x = [a for a in iterable while a]
>
> which equates to:
>
> x = []
> for a in iterable:
>    if not a:
>        break
>    x.append(a)
>
> It does has a few things going for it.  It doesn't add any new keywords, nor does it change the meaning of any currently valid program.  Whether it's sufficiently useful in general is another question :-)  In the specific case I'm looking at now, I've got this annoying lump of code:
>
>        valid_answers = []
>        for p in pairs:
>            if not all(p):
>                break
>            valid_answers.append(p)
>
> which could be rewritten as:
>
>        valid_answers = [p for p in pairs while all(p)]
>
> pairs is a list of tuples.  I need the leading portion of the list where all elements of the tuple are string non-zero-length strings.  Obviously, you'd do the corresponding generator expression as well.

valid_answers = list(itertools.takewhile(all, pairs))



More information about the Python-list mailing list