# Examples of numpy.linspace() in Python

The numpy.linspace() function returns an 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

At 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()``````

Ouput:

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

## Conclusion

At this point you should have a better understanding of some of major use cases of np.linspace(). If you’d like to learn more about NumPy and Python, please check out our NumPy topic page and Python category page for more tutorials and quick examples.

Subscribe
Notify of 