# [Tutor] Re: range() or xrange() for non-integers?

Andrei project5 at redrival.net
Sun Sep 14 10:09:02 EDT 2003

```Terry Carroll wrote:
> On Sat, 13 Sep 2003, Bob Gailer wrote:
>
>
>>for x in xrange(-8.0, 8.0, 1.0):
>>     print x/2
>
>
> Thanks.
>
> I'd thought of something along those lines, but that seems even worse for
> my particular application.  I was going to need to vary the step to find
> the optimal one.  (The actual application is to generate points to graph
> the x-component of electrical field generated by two particles.)  So My
> first cut might be varying by .5, another by .1, etc.  To have to vary by
> 1 and change the start and end points and an inner divisor to compensate
> seems very kludgy to me.

Why don't you just build your own rangef() function which returns a list?

>>> def rangef(min, max, step):
...     result = []
...     while 1:
...         result.append(min)
...         min = min+step
...         if min>=max:
...             break
...     return result
...
>>> rangef(2,3,.2)
[2, 2.2000000000000002, 2.4000000000000004, 2.6000000000000005, 2.8000000000000007]

If desired, you can add some parameter checking routines so that min<max and
step>0 or whatever you need. You could also do (with a generator):

>>> def rangef(min=1, max=2, step=.2):
...     while min<max:
...         yield min
...         min = min+step
...
>>> for item in rangef(3, 5, .3):
...     print item
...
3
3.3
3.6
3.9
4.2
4.5
4.8

--
Yours,

Andrei

=====
Mail address in header catches spam. Real contact info (decode with rot13):
cebwrpg5 at bcrenznvy.pbz. Fcnz-serr! Cyrnfr qb abg hfr va choyvp cbfgf. V ernq gur
yvfg, fb gurer'f ab arrq gb PP.

```