The arange() method creates an array with evenly spaced elements as per the interval.
arange() Syntax
The syntax of arange() is:
numpy.arange(start = 0, stop, step = 1, dtype = None)
arange() Argument
The arange() method takes the following arguments:
start(optional)- the start value of the interval range (intorreal)stop- the end value of the interval range (exclusive) (intorreal)step(optional)- step size of the interval (intorreal)dtype(optional)- type of output array(dtype)
Notes:
stepcan't be zero. Otherwise, you'll get aZeroDivisionError.- If
dtypeis omitted,arange()will determine the type of the array elements from the types of other parameters. - In
arange(), thestopvalue is exclusive.
arange() Return Value
The arange() method returns an array of evenly spaced values.
Example 1: Create a 1-D Array Using arange
Output
[0 1 2 3 4] [5 6 7 8 9] [ 5 7 9 11 13]
Note:
If only one argument is passed, it represents the stop value with start = 0 and step = 1.
If two arguments are passed, they represent the start and the stop values with step = 1.
Example 2: Create a Floating Point 1-D Array Using arange
Output
[0. 0.2 0.4 0.6 0.8]
Example 3: Passing Negative Valued Arguments in arange
Output
[-5 -3 -1 1 3] [-15 -13 -11 -9 -7] [15 13 11 9 7]
Note:
- When passing negative integers in the
startand thestopvalue innumpy.arange(), they are treated the same as positive integers. - Passing a negative integer as
stepsize creates an array in descending order.
Key Differences Between arange and linspace
Both np.arange() and np.linspace() are NumPy functions used to generate numerical sequences, but they have some differences in their behavior.
arange()generates a sequence of values fromstarttostopwith a givenstepsize whereaslinspacegenerates a sequence ofnumevenly spaced values fromstarttostop.arange()excludesstopvalue whereaslinspaceincludesstopvalue unless specified otherwise byendpoint = False
Let us see an example.
Output
Using arange: [10 14 18 22 26 30 34 38 42 46] Using linspace: [10. 23.33333333 36.66666667 50. ]