Python allows you to create and use range of values as arrays or lists in your scripts and programs. Generally, people use an integer as a step value between two consecutive value of range. For example, they may create a range 1, 2, 3, … 100. But sometimes you may need to use a decimal step value for range in Python. For example, 0, 0.1, 0.2, 0.3… 1.0. In this article, we will learn how to use decimal step value for range in Python.
How to Use Decimal Step Value for Range in Python
There are several ways to use decimal step value for range in Python. You can use Numpy library for this purpose. It contains arange() function that allows you to create a range of values using decimal step.
Here is the syntax of arange() function.
arange(starting, end, step)
Here is an example of arange() function.
>>> import numpy as np >>> np.arange(0.0, 1.0, 0.1) array([ 0.0 , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
You can also use linspace function from Numpy library that allows you to do the same thing. Its syntax is
linspace(start, end, num)
In the above function, linspace() function divides the difference between end and start into num equal parts. It also allows you to specify whether you want to include endpoints or not.
>>> np.linspace(0,1,11) array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9, 1.0 ]) >>> np.linspace(0,1,10,endpoint=False) array([ 0. , 0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9])
If you don’t want to use a python library you can also use list comprehensions to generate this list. Here is an example to generate a range of number of 0.1 step each. range() function can only generate a range of integers, not floating point numbers, so you need to multiply it with a floating point number to use a decimal step.
[x * 0.1 for x in range(0, 10)]
If you need to create a really large range of values using decimal step, you can modify the above code to use a generator function, which consumes very less memory.
xs = (x * 0.1 for x in range(0, 10)) for x in xs: print(x)
In this article, we have learnt how to use decimal step value in Python.