'while' in list comprehension?
Michael Geary
Mike at DeleteThis.Geary.com
Fri Oct 24 11:44:29 EDT 2003
> > > 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.
Here's an idea that might avoid this bit of confusion:
foo = [ i for i in bar until len(i) == 0 ]
That also makes the conditional test the same as used in the "if/break"
form.
Hmm... Would this mean that "until" would have to become a reserved word?
Maybe not such a good idea if that's the case.
-Mike
More information about the Python-list
mailing list