We use np.arange() to create arrays with numbers in a sequence. It helps us quickly make lists of numbers for calculations or analysis.
np.arange() for range arrays in NumPy
import numpy as np array = np.arange(start, stop, step)
start is where the sequence begins (default is 0).
stop is where the sequence ends but is not included.
step is how much to increase each time (default is 1).
import numpy as np array = np.arange(5) print(array)
import numpy as np array = np.arange(2, 7) print(array)
import numpy as np array = np.arange(1, 10, 2) print(array)
import numpy as np array = np.arange(10, 5, -1) print(array)
This program shows how to create arrays with np.arange() using different starts, stops, and steps. It also shows what happens if start and stop are the same.
import numpy as np # Create an array from 0 to 9 array_start_0 = np.arange(10) print('Array from 0 to 9:', array_start_0) # Create an array from 5 to 14 array_start_5 = np.arange(5, 15) print('Array from 5 to 14:', array_start_5) # Create an array from 0 to 5 with step 0.5 array_step_half = np.arange(0, 5, 0.5) print('Array from 0 to 5 with step 0.5:', array_step_half) # Create an empty array when start equals stop array_empty = np.arange(3, 3) print('Empty array when start equals stop:', array_empty)
Time complexity: Creating an array with np.arange() is fast and runs in O(n), where n is the number of elements.
Space complexity: The array uses memory proportional to the number of elements created.
A common mistake is forgetting that the stop value is not included in the array.
Use np.arange() when you want a sequence of numbers with a fixed step. For floating point steps, sometimes np.linspace() is better to avoid rounding issues.
np.arange() creates arrays with numbers in a range you choose.
The stop value is not included in the array.
You can set the start, stop, and step to control the sequence.