# Examples of numpy.linspace() in Python

Last updated on February 23, 2022 Napoleon Loading...

The numpy.linspace() function returns a ndarray with equally spaced intervals between the start and stop values. That ndarray is a vector space, also known as a linear space. That’s why the function is named linspace.

This article goes over the syntax as well as a few examples of using the numpy.linspace() function in Python programs.

## Syntax

First, let’s take a look at numpy.linspace() syntax:

``````numpy.linspace(
start,
stop,
num=50,
endpoint=True,
retstep=False,
dtype=None,
axis=0
)``````

Parameters:

## Example 1: Basic Usage

The code:

``````import numpy as np

x1 = np.linspace(start = 0, stop = 100, num = 11)
print(x1)

# set endpoint to False
x2 = np.linspace(start = 0, stop = 100, num = 11, endpoint = False)
print(x2)

# set retstep to True
x3 = np.linspace(0, 100, num = 11, retstep = True)
print(x3)``````

Output (x1, x2, and x3 in the corresponding order):

``````[  0.  10.  20.  30.  40.  50.  60.  70.  80.  90. 100.]

[ 0.          9.09090909 18.18181818 27.27272727 36.36363636 45.45454545
54.54545455 63.63636364 72.72727273 81.81818182 90.90909091]

(array([  0.,  10.,  20.,  30.,  40.,  50.,  60.,  70.,  80.,  90., 100.]), 10.0)``````

## Example 2: Making a bar chart with np.linspace() and Matplotlib

The code:

``````import numpy as np
import matplotlib.pyplot as plt

N = 11
x = np.linspace(0, 100, num = N)
y = x ** 3 - 2 * x + 7

ax = plt.subplot()
ax.bar(x, y, width=4)

ax.set_xlabel('X')
ax.set_ylabel('Y')

plt.show()``````

Output:

## Example 3: endpoint = True vs endpoint = False graphical representation

The code:

``````import numpy as np
import matplotlib.pyplot as plt

N = 9
x1 = np.linspace(0, 8, num = N)
x2 = np.linspace(0, 8, num = N, endpoint = False)

y = np.ones(N)

plt.plot(x1, y, 'o')
plt.plot(x2, y + 1, 'o')
plt.ylim([0, 3])

plt.show()``````

Output:

You can find more information about numpy.linspace in the Numpy official manual.

## Conclusion

At this point, you should have a better understanding of some of the major use cases of np.linspace(). If you’d like to learn more new and interesting stuff in the Python world, take a look at the following articles:

You can also check out our Machine Learning category page or Python category page for more tutorials and examples.

Subscribe
Notify of 