'while' in list comprehension?

Francis Avila francisgavila at yahoo.com
Wed Oct 22 17:23:36 EDT 2003


"Emile van Sebille" <emile at fenx.com> wrote in message
news:bn6k9i$tftt3$1 at ID-11957.news.uni-berlin.de...
> jsaul asks...
> > would then turn into
> >
> >     foo = [ i for i in bar while len(i)>0 ]
> >
> > Is there any reason for not having this kind of thing? I actually
> > miss it pretty often.
> >
>
>
> How is this different from:
>
>      foo = [ i for i in bar if len(i) ]
>
> Emile van Sebille
> emile at fenx.com
>

The idea is that 'while' stops iterating through the list when the condition
isn't met. 'if' just doesn't output anything. e.g.:

>>> bar = ['this', 'is', 'a', 'list', '', 'see?']
>>> [i for i in bar if len(i)]
['this', 'is', 'a', 'list', 'see?']
>>> [i for i in bar while len(i)]  # Pretend
['this', 'is', 'a', 'list']

What's your typical use for this?

I guess I see nothing really wrong with it, although I thought list
comprehensions were supposed to make the iteration transparent--'while'
kinda destroys the illusion.  But these are the only two looping constructs
that make sense in a list comprehension, so why not support both?  OTOH,
'while' makes no sense in a dictionary comprehension (and presumably we'll
have those one day.)





More information about the Python-list mailing list