Arrays are not native data types in Python. To use an array in Python, we need to use the numpy library. For large arrays, a vectorized numpy operation is the fastest.
The np.arange() function returns an array with evenly spaced elements as per the interval. To use the np.arange() method in your Python script, you have to import a Numpy library.
import numpy as np
Let’s see the syntax of numpy arange() method.
numpy.arange(start, stop, step, dtype=None)
import numpy as np arr = np.arange(start=0, stop=11, step=2) print(arr)
[ 0 2 4 6 8 10]
You can see that we got the evenly spaced array elements in the output.
The np.arange() method includes the start value but excludes the endpoint value. To include the endpoint in np.arange()’s output, set the upper limit by +1 that way, it will include your desired value.
To create a sequence of numbers, starting from 0 by default, and increments by 1, use the built-in Python range() function.
range(start, stop, step)
data = range(6) for i in data: print(i)
0 1 2 3 4 5
In this example, we called the range() function with only one argument that returns a sequence of numbers from 0 to 5. Here too, if you want to include the endpoint then you have to set the upper limit by +1, and that way, it will include your desired endpoint in the output.
np.arange vs range
- The main difference between range and np.arange is that the range() function returns an iterator instead of a list and np.arange() function gives a numpy array that consists of evenly spaced values within a given interval.
- The range() function generates a sequence of integer values lying between a certain range.
- The range() is a built-in function whereas arange() is a numpy library function.
- The range() function is more convenient when you need to iterate values using the for loop. The np.arange() function is more useful when you are working with arrays and you need to generate an array based on a specific sequence.
That’s it for np.arange vs range comparison article.