Today we are going to learn NumPy arange to create NumPy array that is available in the Numpy python library. It is used to create a NumPy sequential array. To use first need to install Numpy after installation we can import in our program.
What is np.arange() function
Numpy library provides an np.arange() function To create a pattern of numbers, where you can specify the start and stop values. Then you can provide the step size to create the pattern. It returns objects that contain evenly spaced values defined within the passing range and takes four arguments(start, stop, step, type).
syntax for np.arange() function
arange(start, stop, step, dtype)
Parameters
- start: It is an optional parameter, the start of inetrval defualt values is 0.
- stop: It optional parameter indicates the end of the interval
- step: The space between values
- dtype: type of return array.
1.Create NumPy array of evenly spaced Numbers Using np.arange()
The python program we will create an array of numbers from 1 to 20 with a step size of 2, which means even numbers between 2 to 20,
We have created a Numpy array by including the endpoint that is 20. It will start from 2 and the space between elements would be 2 and it will stop at 20.
# start from 2 and end at 20 with step size of 2. 20 is not included
even_numbers = np.arange(2, 20, 2)
print("Even numbers using arange",even_numbers)
Output
Even numbers using arange [ 2 4 6 8 10 12 14 16 18]
2. Create a float NumPy array Using np.arange()
arange() function can work with float numbers also. let us see this with the example below. In this python program example, we are trying to create an array with floating numbers between 0 to 2 and with a step size of 0.3.
import numpy as np
float_numbers = np.arange( 0, 2, 0.3)
print("Float numbers using arange",float_numbers)
Output of the above program will be:
Float numbers using arange [0. 0.3 0.6 0.9 1.2 1.5 1.8]
3.NumPy.arange 2D array
In this python program example, we will learn how to create a 2D Numpy array by using np. arange() function.We are running a for loop for range 0 to 5.
x = 0
y= 5
for x in range(5):
mylist = np.arange(x, y)
x += 1
y += 1
print(np.array(mylist))
Output
[0 1 2 3 4]
[1 2 3 4 5]
[2 3 4 5 6]
[3 4 5 6 7]
[4 5 6 7 8]