Looping in Python
Andrae Muys
amuys at shortech.com.au
Mon Dec 17 23:36:33 EST 2001
"basegmez" <fb at ultranet.com> wrote in message news:<9vl8os$gcs$1 at bob.news.rcn.net>...
> If everything is an object in Python then why not:
>
> Syntax:
>
> loop(start=0, stop, step=1):
> (loop.count and loop.value automagically generated by Python,
> loop count starts from 1 and incremented by 1,
> loop value starts from start value and incremented by step value,
> stop value is a long integer)
<SNIP>
> If you feel like pushing it, "loop.start", "loop.stop" and "loop.step" may
> be added.
> If it could implement floating point step values, it would be even better
> but I am not sure if this would be feasible.
> I realized that there have been some lengthy (to put it mildly) discussions
> of loop structures, if this is already proposed and rejected, just ignore
> it. If not, someone may be able to come up with better alternatives to
> "loop.count" and "loop.value" even the "loop" keyword. This was the most
> Pythonic way I could come up with.
With python 2.2 we now have access to Generators, which can achieve
the same thing. Consider the following...
from __future__ import generators
def frange(start,stop,step=1.0):
while start < stop:
yield start
start += step
l = []
for i in frange(1.0, 10.0):
l.append(i)
print l
[1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0]
l = [i for i in frange(1.0, 10.0)]
print l
l = []
loop = frange(1.0,10.0):
l.append(loop.next())
l.append(loop.next())
l.append(loop.next())
print l
[1.0, 2.0, 3.0]
Andrae Muys
More information about the Python-list
mailing list