How do I use numpy.arange to include the endpoint?

Numpy.arange is a built-in function in the Numpy library that allows you to generate a sequence of numbers within a specified range. The endpoint can be included by setting the third parameter of np.arange to False, which will create a sequence of numbers up to but not including the endpoint. Alternatively, if the third parameter is set to True, the endpoint will be included in the sequence. This parameter is optional and defaults to False.


The NumPy arange function can be used to create a sequence of values.

By default, this function doesn’t include the endpoint as part of the sequence of values.

There are two ways to get around this:

Method 1: Add the Step Size to the Endpoint

np.arange(start, stop + step, step)

Method 2: Use the linspace Function Instead

np.linspace(start, stop, num)

The following examples show how to use each method in practice.

Example 1: Add Step Size to the Endpoint

Suppose we would like to create a sequence of values ranging from 0 to 50 with a step size of 5.

If we use the NumPy arange function, the endpoint of 50 will not be included in the sequence by default:

import numpy as np

#specify start, stop, and step size
start = 0
stop = 50
step = 5

#create array
np.arange(start, stop, step)

array([ 0,  5, 10, 15, 20, 25, 30, 35, 40, 45])

To include the endpoint of 50, we can simply add the step size to the stop argument:

import numpy as np

#specify start, stop, and step size
start = 0
stop = 50
step = 5

#create array
np.arange(start, stop + step, step)

array([ 0,  5, 10, 15, 20, 25, 30, 35, 40, 45, 50])

Notice that the endpoint of 50 is now included in the sequence of values.

Note: You can find the complete documentation for the NumPy arange() function .

Example 2: Use the linspace Function Instead

The following code shows how to use this function to create a sequence of values ranging from 0 to 50:

import numpy as np

#specify start, stop, and number of total values in sequence
start = 0
stop = 50
num = 11

#create array
np.linspace(start, stop, num)

array([ 0.,  5., 10., 15., 20., 25., 30., 35., 40., 45., 50.])

Notice that the endpoint of 50 is included in the sequence of values by default.

Note: You can find the complete documentation for the NumPy arange() function .

The following tutorials explain how to perform other common operations in NumPy:

x