To work with an array in Python, use the numpy library. The numpy provides an important data type called a ndarray.
To create an array based on numerical routines in Python, use the np.arange() function. The numpy.arange() function returns an instance of ndarray with evenly spaced values.
import numpy as np arr = np.arange(start=0, stop=10, step=2) print(arr)
[0 2 4 6 8]
In this example, np.arange() accepts three arguments.
The start parameter specifies from where you want to start the range of your array.
The stop argument specifies what is the endpoint of your array.
The step argument specifies the spacing between every two consecutive values in the array. The step cannot be 0. Otherwise, you’ll get a ZeroDivisionError.
In our code, we started with 0 up to 10 and the spacing is 2 that means first value is 0 and then space of 2 which means the next value is 0 + 2 = 2 and then 2 + 2 = 4 and then 4 + 2 = 6 and 6 + 2 = 8.
The endpoint is 10, which is not included in the output because the np.arange() function does not include the endpoint.
np.arange include endpoint
To include endpoint in np.arange() function, increase your upper bound by one increment. By default, the np.arange() function does not allow us to include an endpoint, but by increasing your upper value, you can get your endpoint.
For example, in the above code, if you want to include 10 in your output, then you have to set the upper value or stop value to 11. That way, it will include 10 in your output.
import numpy as np arr = np.arange(start=0, stop=11, step=2) print(arr)
[ 0 2 4 6 8 10]
Woohoo! We get the endpoint in the output as expected in the numpy arange() function.
That’s it for np.arange include endpoint tutorial.
Krunal Lathiya is an Information Technology Engineer. By profession, he is a web developer with knowledge of multiple back-end platforms including Python. Krunal has written many programming blogs which showcases his vast knowledge in this field.