NumPy arange()

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 (int or real)
  • stop- the end value of the interval range (exclusive) (int or real)
  • step(optional)- step size of the interval (int or real)
  • dtype(optional)- type of output array(dtype)

Notes:

  • step can't be zero. Otherwise, you'll get a ZeroDivisionError.
  • If dtype is omitted, arange() will determine the type of the array elements from the types of other parameters.
  • In arange(), the stop value 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 start and the stop value in numpy.arange(), they are treated the same as positive integers.
  • Passing a negative integer as step size 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 from start to stop with a given step size whereas linspace generates a sequence of num evenly spaced values from start to stop.
  • arange() excludes stop value whereas linspace includes stop value unless specified otherwise by endpoint = 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.        ]