Is there a way to step between 0 and 1 by 0.1?
I thought I could do it like the following, but it failed:
for i in range(0, 1, 0.1):
print i
Instead, it says that the step argument cannot be zero, which I did not expect.
Is there a way to step between 0 and 1 by 0.1?
I thought I could do it like the following, but it failed:
for i in range(0, 1, 0.1):
print i
Instead, it says that the step argument cannot be zero, which I did not expect.
Python's range() can only do integers, not floating point. In your specific case, you can use a list comprehension instead:
(Replace the call to range with that expression.)
For the more general case, you may want to write a custom function or generator.
It can be done using Numpy library. arange() function allows steps in float. But, it returns a numpy array which can be converted to list using tolist() for our convenience.
start and stop are inclusive rather than one or the other (usually stop is excluded) and without imports, and using generators
This one liner will not clutter your code. The sign of the step parameter is important.
Rather than using a decimal step directly, it's much safer to express this in terms of how many points you want. Otherwise, floating-point rounding error is likely to give you a wrong result.
You can use the
linspace
function from the NumPy library (which isn't part of the standard library but is relatively easy to obtain).linspace
takes a number of points to return, and also lets you specify whether or not to include the right endpoint:If you really want to use a floating-point step value, you can, with
numpy.arange
.Floating-point rounding error will cause problems, though. Here's a simple case where rounding error causes
arange
to produce a length-4 array when it should only produce 3 numbers:The range() built-in function returns a sequence of integer values, I'm afraid, so you can't use it to do a decimal step.
I'd say just use a while loop:
If you're curious, Python is converting your 0.1 to 0, which is why it's telling you the argument can't be zero.