NumPy arrange functions allow you to create an array with equal or evenly spaced values. You can consider it as a built-in python function range() but it returns array instead a list return by range() function. In this tutorial you will implement numpy arrange() function with steps.
Syntax of Numpy arrange function
The syntax of the arrange() function is below.
numpy.arange([start, ]stop, [step, ]dtype=None)
Here’s what each argument means:
- start (optional): The start of the interval. If not specified, it defaults to 0.
- stop: The end of the interval. The generated values are up to, but not including, this value.
- step (optional): Spacing between values. If not specified, it defaults to 1.
- dtype (optional): The data type of the output array. If not specified, the data type is inferred from the other input arguments.
Steps to Implement Numpy arrange Function
Step 1: Import NumPy
The first step is to import the NumPy package. You should make sure you have NumPy installed, and then import it into your Python script or Jupyter Notebook.
import numpy as np
Step 2: Use arange function
The arange
function takes three arguments: start
, stop
, and step
. It generates values from start
to stop - step
with a step size of step
. Use the lines below of code to generate the numpy array.
start_value = 0
stop_value = 20
step_size = 4
result_array = np.arange(start_value, stop_value, step_size)
In this example, result_array
will be [0, 4, 8, 12, 16 ]
.
If you omit the step
argument, it defaults to 1
result_array_default_step = np.arange(start_value, stop_value)
Output
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19]
Step 3: Print or display the result
Now you can print the resulting array or use it in further calculations and manipulation.
print(result_array)
You can also use the array for various mathematical operations or as needed in your application.
Below is the complete code.
import numpy as np
# Define parameters
start_value = 0
stop_value = 20
step_size = 4
# Use arange function
result_array = np.arange(start_value, stop_value, step_size)
# Print the result
print(result_array)
Output
[ 0 4 8 12 16]
You can Adjust the start_value
, stop_value
, and step_size
according to your requirements.
Conclusion
Numpy arange function is the quick method to create a numpy array whose difference is the same. In this tutorial you have learned the syntax of the numpy arange() function. The above steps allow you to implement the numpy arange function.
Leave a Reply