Looping in Python

Jeff Shannon jeff at ccvcorp.com
Thu Dec 20 19:31:30 CET 2001


Andrae Muys wrote:

> 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]

Of course, using floating point steps has its dangers:

for i in frange(1.0, 2.0, 0.1):
    repr( i )

'1.0'
'1.1000000000000001'
'1.2000000000000002'
'1.3000000000000003'
'1.4000000000000004'
'1.5000000000000004'
'1.6000000000000005'
'1.7000000000000006'
'1.8000000000000007'
'1.9000000000000008'

This being inherent in the nature of floating-point, of course, but someone's bound to
complain... ;)  Your frange() generator also doesn't handle negative steps, obviously,
but that should be easy enough to fix.

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list