Half-baked idea: list comprehensions with "while"

Kiuhnm kiuhnm03.4t.yahoo.it
Thu Apr 26 13:44:31 EDT 2012


On 4/26/2012 19:02, Roy Smith 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.

I think it's a nice idea. In the meantime, try this way:
   valid_answers = list(takewhile(all, pairs))

Kiuhnm



More information about the Python-list mailing list