Half-baked idea: list comprehensions with "while"

Mark Lawrence breamoreboy at yahoo.co.uk
Thu Apr 26 13:14:25 EDT 2012


On 26/04/2012 18: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.

itertools.takewhile ?

-- 
Cheers.

Mark Lawrence.




More information about the Python-list mailing list