Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Half-baked idea: list comprehensions with "while"

26 views
Skip to first unread message

Roy Smith

unread,
Apr 26, 2012, 1:02:41 PM4/26/12
to
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.

Kiuhnm

unread,
Apr 26, 2012, 1:44:31 PM4/26/12
to
I think it's a nice idea. In the meantime, try this way:
valid_answers = list(takewhile(all, pairs))

Kiuhnm

Paul Rubin

unread,
Apr 26, 2012, 1:48:58 PM4/26/12
to
Roy Smith <r...@panix.com> writes:
> x = [a for a in iterable while a]

from itertools import takewhile

x = takewhile(bool, a)

Kiuhnm

unread,
Apr 26, 2012, 1:57:21 PM4/26/12
to
I see that as a 'temporary' solution, otherwise we wouldn't need 'if'
inside of list comprehensions either.

Kiuhnm

Miles Rout

unread,
Apr 27, 2012, 5:49:53 AM4/27/12
to miles...@gmail.com
We have if inside list comprehensions? I didn't know that, could you
provide an example?

Kiuhnm

unread,
Apr 27, 2012, 6:56:04 AM4/27/12
to
elems = [4, 1, 9, 6, 3, 8, 3, 9, 2]
small_elems = [x for x in elems if x < 5]
print str(small_elems) # 4, 1, 3, 3, 2

#leading_small_elems = [x for x in elems while x < 5]
#print str(leading_small_elems) # 4, 1

Kiuhnm
0 new messages