'while' in list comprehension?
jsaul
jsaul at gmx.de
Fri Oct 24 08:59:23 EDT 2003
* Terry Reedy [2003-10-23 04:57]:
> "jsaul" <jsaul at gmx.de> wrote in message
> news:20031022175924.GA10716 at jsaul.de...
> > wouldn't it be useful to have a 'while' conditional in addition to
> > 'if' in list comprehensions?
> >
> > foo = []
> > for i in bar:
> > if len(i) == 0:
> > break
> > foo.append(i)
> >
> > would then turn into
> >
> > foo = [ i for i in bar while len(i)>0 ]
>
> while is simply not same as if: break!
> if executes once for each value of i, while indefinitely.
> If you translate back by current rule, which will not change, you get:
>
> foo = []
> for i in bar:
> while len(i) >0:
> foo.append(i)
I agree that 'while' cannot not just be considered a replacement
for 'if'. However, adding a 'while' conditional to list
comprehensions would very unlikely be misunderstood as another
(infinite) loop. Instead, I find the above 'while' example about
as intuitive as is the case with 'if'. It simply means that under
a certain condition the loop will be ended, which is just what
most people would probably expect.
Anyway, thanks a lot to all who replied! What is your opinion
after this discussion, write a PEP or just forget about it?
Cheers, jsaul
More information about the Python-list
mailing list