numpy.arange() function creates an array of evenly spaced values within a given interval. It is similar to Python's built-in range() function but returns a NumPy array instead of a list.
Example: This example creates a NumPy array containing values from 5 to 9 using numpy.arange().
import numpy as np
a = np.arange(5 , 10)
print(a)
Output
[5 6 7 8 9]
Syntax
numpy.arange(start, stop, step, dtype=None)
Parameters:
- start (optional): The starting value of the sequence. Default is 0.
- stop: The endpoint of the sequence, exclusive.
- step (optional): The spacing between consecutive values. Default is 1.
- dtype (optional): The desired data type of the output array.
Return Type: array of evenly spaced values.
Specify Start and Stop
This example shows how np.arange() generates a sequence of integers by specifying only the stop value. By default, the sequence starts from 0 and increases by 1 until the stop value is reached (excluding it).
import numpy as np
sequence = np.arange(10)
print("Basic Sequence:", sequence)
Output
Basic Sequence: [0 1 2 3 4 5 6 7 8 9]
Explanation: np.arange(10) creates values starting from 0 up to 9.
Floating-Point Step Size
np.arange() can also generate sequences with floating-point values by specifying a decimal step size.
import numpy as np
sequence = np.arange(0, 1, 0.2)
print("Floating-Point Sequence:", sequence)
Output
Floating-Point Sequence: [0. 0.2 0.4 0.6 0.8]
Explanation: sequence starts at 0 and increases by 0.2 and value 1 is excluded from the output.
Combining with Conditional Filtering
NumPy allows combining arange() with conditional filtering to extract specific values from a generated sequence.
import numpy as np
sequence = np.arange(0, 20, 3)
filtered = sequence[sequence > 10]
print("Filtered Sequence:", filtered)
Output
Filtered Sequence: [12 15 18]
Explanation:
- np.arange(0, 20, 3) generates numbers starting from 0 with a step of 3.
- The condition sequence > 10 filters only values greater than 10.