It is common to express for loops as list comprehensions:
mylist=[]
for i in range(30):
mylist.append(i**2)
This is equivalent to:
mylist = [i**2 for i in range(30)]
Is there any sort of mechanism by which this sort of iteration could be done with a while loop?
mylist=[]
i=0
while i<30:
mylist.append(i**2)
i+=1
Of course with this simple example it's easy to translate to a for
loop and then to a list comprehension, but what if it isn't quite so easy?
e.g.
mylist = [i**2 while i=0;i<30;i++ ]
(Of course the above pseudo-code isn't legitimate python) (itertools
comes to mind for this sort of thing, but I don't know that module terribly well.)
EDIT
An (very simple) example where I think a while comprehension would be useful would be:
dt=0.05
t=0
mytimes=[]
while t<maxtime:
mytimes.append(t)
t+=dt
This could translate to:
dt=0.05
t=0
nsteps=maxtime/dt
mytimes=[]
for t in (i*dt for i in xrange(nsteps)):
mytimes.append(t)
which can be written as a (compound) list comprehension:
nsteps=maxtime/dt
mytimes=[t for t in (i*dt for i in xrange(nsteps)]
But, I would argue that the while loop is MUCH easier to read (and not have index errors) Also, what if your object (dt) supports '+' but not '*'? More complicated examples could happen if maxtime
somehow changes for each iteration of the loop...