How do I use a decimal step value for range()?
You can use the numpy library's arange() function to specify a decimal step value for the range.
You can use the numpy library's arange() function to specify a decimal step value for the range. numpy.arange(start, stop, step) generates an array with a range of values, similar to the built-in range() function.
For example, to generate a range of values from 0 to 1 with a step of 0.1, you would use the following code:
Generate a range of values by numpy in Python
import numpy as np
for i in np.arange(0, 1, 0.1):
print(i)This will output:
0.0
0.1
0.2
0.3
0.4
0.5
0.6
0.7
0.8
0.9Note that Python's built-in range() function strictly requires integer arguments and will raise a TypeError with float steps. If you prefer not to use external libraries, you can generate decimal steps using a list comprehension or a custom generator. For example:
Generate a range of values by list comprehension in Python
# Using a list comprehension
[round(i * 0.1, 1) for i in range(10)]This will output:
[0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9]