19

Say I want to loop from 0 to 100 but with a step of 1/2. If you try

for i in range(0, 100, 0.5):
    whatever

Error:

the step must not be 0

Question: Is there any built-in way in Python 2.x to do something like this?

kenlukas
  • 3,616
  • 9
  • 25
  • 36
GeoffDS
  • 1,221
  • 5
  • 19
  • 31
  • Looking at some of the answers this would make an excellent reverse code golf question ... – ktdrv Sep 23 '11 at 16:33

6 Answers6

27

Python2.x:

for idx in range(0, int(100 / 0.5)):

    print 0.5 * idx      

outputs:

0.0

0.5

1.0

1.5

..

99.0

99.5


Numpy:

numpy.arange would also do the trick.

numpy.arange(0, 100, 0.5)
Phoenix
  • 3,996
  • 4
  • 29
  • 40
NPE
  • 486,780
  • 108
  • 951
  • 1,012
  • Interesting approach, but I like it. :) – g.d.d.c Sep 23 '11 at 16:17
  • @NPE Am I missing something here? Here is the result `TypeError: range() integer end argument expected, got float.` – gongzhitaao Nov 09 '13 at 04:35
  • @gongzhitaao: You are quite right, this need an explicit conversion to `int` (see the edit). Since the answer was written over two years ago, I can't remember why I wrote it the way it is. – NPE Nov 09 '13 at 18:54
10

If you have numpy, here are two ways to do it:

numpy.arange(0, 100, 0.5)

numpy.linspace(0, 100, 200, endpoint=False)
Steve Tjoa
  • 59,122
  • 18
  • 90
  • 101
4

You have to use integer steps for range() and xrange(). That's why your 0.5 step gets internally converted to 0 and you get that error. Try for i in [j / 2.0 for j in xrange(100 * 2)]:

ktdrv
  • 3,602
  • 3
  • 30
  • 45
3

You'll have to either create the loop manually, or define your own custom range function. The built-in requires an integer step value.

g.d.d.c
  • 46,865
  • 9
  • 101
  • 111
0
for x in map(lambda i: i * 0.5, range(0,200)):
  #Do something with x
Peter Smith
  • 849
  • 2
  • 11
  • 28
  • `map` and a lambda function for a simple iterable? Looks cool and functional programing-y but, in reality, it would just add unnecessary computational complexity. – ktdrv Sep 23 '11 at 16:22
0

For large ranges it is better to use an generator expression than building a list explicitly:

 for k in ( i*0.5 for i in range(200) ):
     print k

This consumes not much extra memory, is fast und easy to read. See http://docs.python.org/tutorial/classes.html#generator-expressions

rocksportrocker
  • 7,251
  • 2
  • 31
  • 48
  • 3
    In Python 2, you would be defeating the memory savings of a generator expression since range() produces a list; use xrange() instead. In Python 3, xrange() replaces range(). – Ned Deily Sep 23 '11 at 17:48