numpy.arange() in Python | np.arange() in Python

Numpy arange() function is used to generate evenly spaced numeric values within the provided interval. It is one of the ways to generate Numpy array.

Syntax of Numpy arange()

np.arange(start, stop, step, dtype=None)

start parameter is optional and is used to specify the start of interval. Its default value is 0. It is included in the interval.

stop parameter is used to specify the end of interval. It is not included in the interval.

step parameter is optional and is used to specify the step size of the interval. Its default value is 1.

dtype parameter is optional and controls the data type of the resultant Numpy array.

Note: In mathematical terms, numbers generated by np.arange() function belongs to this interval: [start, stop). np.arange() function generates 1-dimensional Numpy array but with the help of np.ndarray.reshape() function you can change it to n-dimensional Numpy array.

Python program to generate Numpy array using np.arange() function

import numpy as np

x = np.arange(1, 10)
print('Numpy array x:', x)
y = np.arange(5, 21, 3).reshape(3, 2)
print('Numpy array y:\n', y)

Output of the above program

Numpy array x: [1 2 3 4 5 6 7 8 9]
Numpy array y:
 [[ 5  8]
 [11 14]
 [17 20]]

The code np.arange(1, 10) generated 1-D Numpy array having values from 1 to 10 but 10 is not included.

The code np.arange(5, 21, 3).reshape(3, 2) generated Numpy array having values from 5 to 21 with a step size of 3 and then converted that 1-D array to 2-D array having 3 rows and 2 columns using reshape() function.

Recommended Posts