How to use arange() function in NumPy to create an array?

Numpy

Today we are going to learn about arange() function available in the Numpy python library.

# using arange() function

Numpy library provides a 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).

The syntax for arange() function:


arange(start, stop, step, dtype)
  • 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.

let us understand this with an example:

# 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)

The above program will create an array of numbers from 1 to 20 with a step size of 2, which means even numbers between 2 to 20.

Even numbers using arange [ 2  4  6  8 10 12 14 16 18]

arange() function can work with float numbers also. let us see this with example below:

import numpy as np

float_numbers = np.arange( 0, 2, 0.3)

print("Float numbers using arange",float_numbers)

In this example we are trying to create an array with floating numbers between 0 to 2 and with a step size of 0.3. Output of the above program will be:

Float numbers using arange [0.  0.3 0.6 0.9 1.2 1.5 1.8]