Half-baked idea: list comprehensions with "while"

R

Roy Smith

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

Miles Rout

Roy Smith said:
x = [a for a in iterable while a]

from itertools import takewhile

x = takewhile(bool, a)

I see that as a 'temporary' solution, otherwise we wouldn't need 'if'
inside of list comprehensions either.

Kiuhnm

We have if inside list comprehensions? I didn't know that, could you
provide an example?
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top