Numpy.arange() method creates an array of evenly spaced values within a specified interval. It is highly efficient for creating arrays with a fixed step size, commonly used in scientific computing and data analysis.
Let’s generate integers from 0 to 3. Here, 4 is exclusive.
import numpy as np print(np.arange(4)) # Output: [0 1 2 3]
Syntax
numpy.arange(start, stop, step, dtype)
Parameters
Argument | Description |
start (optional) | It represents the starting value of the sequence (inclusive).
The default is 0. |
stop (required) | It is the end value of the sequence (exclusive). |
step (optional) |
It represents the spacing between values. Default is 1. |
dtype (optional) |
It is the desired data type of the output array (e.g., int, float). If the dtype is not given, infer the data type from the other input arguments. |
Specifying start and stop
We can specify the starting point and ending point to generate a sequence.
import numpy as np arr = np.arange(18, 22) print(arr) # Output: [18 19 20 21]
Specifying step size
Let’s generate a sequence from 17 to 22 with a step of 2.
import numpy as np arr = np.arange(17, 22, 2) print(arr) # Output: [17 19 21]
Passing ‘float’ arguments
To create a sequence of floating-point numbers, we need to pass the floating value to the np.arange() method.
import numpy as np arr = np.arange(2, 11.1, 3) print(arr) # Output: [ 2. 5. 8. 11.]
Creating a multi-dimensional array
You cannot create a 2D or multi-dimensional array using the arange() method alone, but you can reshape it to 2D using the .reshape() method.
import numpy as np print(np.arange(4).reshape(2, 2)) # Output: # [[0 1] # [2 3]]
Negative Step
You can pass the step as a negative number, so it generates numbers from 6 to 1 (decreasing order).
import numpy as np arr = np.arange(6, 1, -1) print(arr) # Output: [6 5 4 3 2]
Zero step
If you pass the step argument as 0, it returns the ZeroDivisionError: division by zero exception.
import numpy as np try: arr = np.arange(1, 5, 0) except ValueError as e: print(e) # Output: ZeroDivisionError: division by zero
Large step size
What if the step size is larger than stop-start? Well, in that case, the array may contain only the start value or be empty.
import numpy as np arr = np.arange(1, 3, 5) print(arr) # Output: [1]
That’s it.