numpy.arange() : Create a Numpy Array of evenly spaced numbers in Python

Creating a Numpy Array of evenly spaced numbers in Python

This article is all about In this article creating a Numpy array of evenly spaced numbers over a given interval using the function numpy.arrange().

numpy.arrange() :

Numpy module in python provides a function numpy.arrange() to create an Numpy Array of evenly space elements within a given interval. Actually it returns an evenly spaced array of numbers from the range-array starting from start point to stop point with equal step intervals.

Syntax- numpy.arange([start, ]stop, [step, ]dtype=None)

Where 

  • start : Represents the start value of range. (As it’s optional, so if not provided it will consider default value as 0)
  • stop : Represents the end value of range. (Actually it doesn’t include this value but it acts as an end point indicator)
  • step : Represents the spacing between two adjacent values. (As it’s optional, so if not provided it will consider default value as 1)
  • dtype : Represents data type of elements.

But to use this Numpy module we have to import following module i.e.

import numpy as np
Let’s see below examples to understand the concept well.

Example-1 : Create a Numpy Array containing numbers from 4 to 20 but at equal interval of 2

Here start is 4, stop is 20 and step is 2.
So let’s see the below program.
import numpy as np
# Start = 4, Stop = 20, Step Size = 2
#achieving the result using arrange()
sample_arr = np.arange(4, 20, 2)
#printing the output
print(sample_arr)
Output :
[ 4 6 8 10 12 14 16 18]

Example-2 : Create a Numpy Array containing numbers from 1 to 15 but at default interval of 1

Here start is 1, stop is 15 and step is default i.e 1.
So let’s see the below program.
import numpy as np
# Start = 1, Stop = 15, Step Size = 1(default)
#achieving the result using arrange()
sample_arr = np.arange(1, 15)
#printing the output
print(sample_arr)
Output :
[ 1 2 3 4 5 6 7 8 9 10 11 12 13 14]

Example-3 : Create a Numpy Array containing numbers upto 15 but start and step is default

Here start is default i.e 0, stop is 15 and step is default i.e 1.
So let’s see the below program.
import numpy as np
# Start = 0(default), Stop = 15, Step Size = 1(default)
#achieving the result using arrange()
sample_arr = np.arange(15)
#printing the output
print(sample_arr)
Output :
[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]