How to use NumPy arange() method to create arrays in Python?

NumPy is a very powerful Python library that used for creating and working with multidimensional arrays with fast performance. The arange() method provided by the NumPy library used to generate array depending upon the parameters that we provide.

In this tutorial, I am going to show you how to use NumPy arrange() method to create arrays with different types of example in Python. So let’s starts…

The arange method of NumPy can generate an array ranging from a start value to an end value with a step value. We can set the start value, end value and the step value.

The syntax of numpy.arange() method:

Below is given the syntax of the arange() function:

arange(start, stop, step, dtype)

You can see that the numpy.arange() method can accept four parameters. Below are the parameters:

start: This is the optional parameter. It is a number type. This value defines the start value of the array.

stop: Define the stop value of the array. This parameter is required in Numpy arange function.




step: It is an optional parameter and defines the spacing between the values of the array. The default value of the step is 1.

dtype: It defines the type of the output array. It can be int, float etc. If dtype parameter is not given, infer the data type from the other input parameters that we provide.

 

Now let’s understand the arange method with some examples.

Below is the code to show the simplest usage of Numpy arange function:

import numpy as np
numpy_array = np.arange(8)
print(numpy_array)

The output of our program will be:

[0 1 2 3 4 5 6 7]

In our above code, we pass only one parameter inside the NumPy arange function. The parameter is the stop value of our array. So it gives the output that starts from 0 to 7.

 

Now see another example below:

import numpy as np
numpy_array = np.arange(15, 23)
print(numpy_array)

The program will give the output:

[15 16 17 18 19 20 21 22]

In this example, we have passed a start value and a stop value. So we got the output array that starts from 15 and ends before 23. Here we can notice that our array doesn’t end at 23. This is a rule that the array will end just before the stop value. As we haven’t set the step value, so the step value is 1 by default.

 

Now below is another example with a step value:

import numpy as np
numpy_array = np.arange(5, 23, 2)
print(numpy_array)

The output is:

[ 5 7 9 11 13 15 17 19 21]

This time our code generates an array from 5 by stepping 2 between values and stop before 23.

 

I hope you have understood the usage of NumPy arange() method in Python from this tutorial. For better understanding, play with it and practice on your machine.


Leave a Reply

Your email address will not be published. Required fields are marked *