NumPy linspace(): How to Create Arrays of Evenly Spaced Numbers
This tutorial will teach you how to use NumPy linspace() to create an array of evenly spaced numbers in Python.
You’ll learn the syntax of NumPy linspace()
, followed by examples that’ll help you understand how to use it.
Note: To follow along with this tutorial, you need to have Python and NumPy installed.
Don’t have NumPy yet? We’ve put together a quick installation guide for you.
Let’s start!
Install and Import NumPy
Before starting the tutorial, let’s quickly run through the steps to install the NumPy library.
⏩ If you already have NumPy installed, feel free to skip to the next section.
 If you’re using Google Colab—a cloudbased Jupyter notebook environment, you can import NumPy and start coding right away. (recommended for this tutorial ✅)
 If you’d like to set up a local working environment, I recommend installing the Anaconda distribution of Python. Anaconda comes with several useful packages preinstalled. You may download the installer for your Operating System. The setup process takes only a few minutes.⌛
 If you already have Python installed on your computer, you can still install the Anaconda distribution. You may use conda or pip to install and manage packages. You may run one of the following commands from the Anaconda Command Prompt to install NumPy.
# Install NumPy using conda
conda install numpy
# Install NumPy using pip
pip install numpy
As a next step, import numpy
under the alias np
by running the following command. Doing this will help you reference NumPy as np
—without having to type down numpy
every time you access an item in the module.
import numpy as np
Going forward, we’ll use the dot notation to access all functions in the NumPy library like this: np.<funcname>
.
The Case for Evenly Spaced Numbers
When you’re working with NumPy arrays, there are times when you’ll need to create an array of evenly spaced numbers in an interval.
Before we go any further, let’s quickly go over another similar function np.arange()
.
NumPy linspace() vs. NumPy arange()
If you’ve used NumPy before, you’d have likely used np.arange()
to create an array of numbers within a specified range.
You know that
np.arange(start, stop, step)
returns an array of numbers fromstart
up to but not includingstop
, in steps ofstep
; the default step size being 1.
However, the value of step may not always be obvious. Let’s see why this is the case.
For example, if you need 4 evenly spaced numbers between 0 and 1, you know that the step size must be 0.25. But if you’re using np.arange()
, it does not include the stop value of 1. So you will have to pick an interval that goes beyond the stop value.
The following image illustrates a few more examples where you need a specific number of evenly spaced points in the interval [a, b].
Our first example of 4 evenly spaced points in [0,1] was easy enough. You know that the step size between the points should be 0.25.
Suppose you have a slightly more involved example—where you had to list 7 evenly spaced points between 1 and 33. Here, the step size may not be very clear immediately. You can, however, manually work out the value of step
in this case.
However, np.linspace()
is here to make it even simpler for you! 😄
When using np.linspace()
, you only need to specify the number of points in the interval—without worrying about the step size. And you’ll get back the array as desired.
With this motivation, let’s proceed to learn the syntax of NumPy linspace()
in the next section.
Syntax of NumPy linspace()
The syntax for using NumPy linspace()
is shown below:
np.linspace(start, stop, num, endpoint, retstep, dtype, axis)
At the outset, the above syntax may seem very complicated with many parameters.
However, most of them are optional parameters, and we’ll arrive at a much simpler syntax in just a couple of minutes.
Now let’s start by parsing the above syntax:
start
andstop
are the starting and end points of the interval, respectively. Both start and stop can be scalars or arrays. We’ll limit ourselves to scalar start and end values in this tutorial.num
is the number of evenly spaced points. And it is an optional parameter with a default value of 50.endpoint
is also an optional parameter that can be either True or False. The default value is True, which means the end point will be included in the interval by default. However, you may set it to False to exclude the end point.
retstep
is yet another optional parameter that takes the Booleans True or False. When set to True, the step value is returned.dtype
is the data type of the numbers in the array. The type is usually inferred as float and need not be provided explicitly.axis
is another optional parameter denoting the axis along which the numbers should be stored. And this is relevant only when thestart
and thestop
values are arrays themselves.
▶️ So what does np.linspace()
return?
It returns an Ndimensional array of evenly spaced numbers. And if the parameter retstep
is set to True
, it also returns the step size.
Based on the discussion so far, here is a simplified syntax to use np.linspace()
:
np.linspace(start, stop, num)
The above line of code will return an array of
num
evenly spaced numbers in the interval[start, stop]
.
Now that you know the syntax, let’s start coding examples.
How to Create Evenly Spaced Arrays with NumPy linspace()
#1. As our first example, let’s create an array of 20 evenly spaced numbers in the interval [1, 5].
You can specify the values of start
, stop
, and num
as keyword arguments. This is shown in the code cell below:
import numpy as np
arr1 = np.linspace(start = 1,stop = 5,num = 20)
print(arr1)
# Output:
[1. 1.21052632 1.42105263 1.63157895 1.84210526 2.05263158
2.26315789 2.47368421 2.68421053 2.89473684 3.10526316 3.31578947
3.52631579 3.73684211 3.94736842 4.15789474 4.36842105 4.57894737
4.78947368 5. ]
Notice how the numbers in the array start at 1 and end at 5—including both the end points. Also, observe how the numbers, including the points 1 and 5 are represented as float
in the returned array.
#2. In the previous example, you had passed in the values for start
, stop
, and num
as keyword arguments. If you pass in the arguments in the correct order, you might as well use them as positional arguments with only the values, as shown below.
import numpy as np
arr2 = np.linspace(1,5,20)
print(arr2)
# Output:
[1. 1.21052632 1.42105263 1.63157895 1.84210526 2.05263158
2.26315789 2.47368421 2.68421053 2.89473684 3.10526316 3.31578947
3.52631579 3.73684211 3.94736842 4.15789474 4.36842105 4.57894737
4.78947368 5. ]
#3. Now let’s create another array where we set retstep
to True
.
This means that the function will now return both the array and the step. And we can unpack them into two variables arr3
: the array, and step_size
: the returned step size.
The following code cell explains how you can do it.
import numpy as np
arr3, step_size = np.linspace(1,5,20,retstep = True)
print(arr3)
# Output:
[1. 1.21052632 1.42105263 1.63157895 1.84210526 2.05263158
2.26315789 2.47368421 2.68421053 2.89473684 3.10526316 3.31578947
3.52631579 3.73684211 3.94736842 4.15789474 4.36842105 4.57894737
4.78947368 5. ]
# Output:
print(step_size)
0.21052631578947367
#4. As a final example, let us set endpoint
to False
, and check what happens.
import numpy as np
arr4 = np.linspace(1,5,20,endpoint = False)
print(arr4)
# Output:
[1. 1.2 1.4 1.6 1.8 2. 2.2 2.4 2.6 2.8 3. 3.2 3.4 3.6 3.8
4. 4.2 4.4 4.6 4.8]
In the returned array, you can see that 1 is included, whereas 5 is not included. And the last value in the array happens to be 4.8, but we still have 20 numbers.
So far, we’ve only generated arrays of evenly spaced numbers. In the next section, let’s visualize by plotting these numbers.
How to Plot Evenly Spaced Numbers in an Interval
In this section, let us choose [10,15] as the interval of interest. And then, use np.linspace()
to generate two arrays, each with 8 and 12 points, respectively.
After this is complete, we can use the plotting function from the matplotlib
library to plot them.
For clarity, we’ll clamp the two arrays of N1 = 8 and N2 = 12 evenly spaced points at different positions along the yaxis.
The following code snippet demonstrates this.
import numpy as np
import matplotlib.pyplot as plt
N1 = 8
N2 = 12
a = 10
b = 15
y1 = np.zeros(N1)
y2 = np.zeros(N2)
x1 = np.linspace(a, b, N1)
x2 = np.linspace(a, b, N2)
plt.plot(x1, y10.5, 'o')
plt.plot(x2, y2 + 0.5, 'o')
plt.ylim([1, 1])
plt.title(f'Evenly Spaced Numbers in the Interval [{a},{b}]')
plt.xlabel('Interval')
plt.show()
Generating evenly spaced points can be helpful when working with mathematical functions. We’ll learn about that in the next section.
How to Use NumPy linspace() with Math Functions
After you’ve generated an array of evenly spaced numbers using np.linspace()
, you can compute the values of mathematical functions in the interval.
In the code cell below, you first generate 50 evenly spaced points in the interval 0 to 2π. And then create the array y
using np.sin()
on the array x
. Note that you may skip the num
parameter, as the default value is 50. We’ll still use it explicitly.
As a next step, you can plot the sine function in the interval [0, 2π]. To do this, you can use matplotlib, as in the previous example. Specifically, the plot()
function in matplotlib.pytplot
is used to create a line plot.
import numpy as np
import matplotlib.pyplot as plt
N = 50
a = 0.0
b = 2*np.pi
x = np.linspace(a, b, N)
y = np.sin(x)
plt.plot(x, y, marker = "o")
plt.ylim([1, 1])
plt.title(f'y = sin(x)')
plt.xlabel('x >')
plt.show()
Now, run the above code by setting N
equal to 10. You’ll get the plot as shown in the figure below.
And you can see that the plot is not very smooth—as you’ve only picked 10 points in the interval.
In general, the larger the number of points you consider, the smoother the plot of the function will be.
Conclusion
Here’s a summary of what we’ve learned.
 np.linspace(start, stop, num) returns an array of num evenly spaced numbers in the interval [start, stop].
 Set the optional parameter endpoint to False to exclude stop, and set the interval to [start, stop).
 Set retstep to True optionally to get the step size.
 Generate evenly spaced arrays using np.linspace(), and then use the array with mathematical functions.
I hope you now understand how np.linspace() works. You may choose to run the above examples in the Jupyter notebook. Check out our guide on Jupyter notebook, or other Jupyter alternatives you can consider.
See you all soon in another Python tutorial. Until then, keep coding!😀
 Tagged in:
 Python
More great readings on Development

9 Deployment Automation Platforms for Modern ApplicationsTalha Khalid on May 17, 2022

15 Best JavaScript (JS) UI Libraries to Build Modern ApplicationsDurga Prasad Acharya on May 17, 2022

12 NoSQL Database for Your Next Modern ProjectAnkush Das on May 13, 2022

An InDepth Guide on the Types of Blockchain NodesDurga Prasad Acharya on May 12, 2022

3 Ways to Multiply Matrices in PythonBala Priya C on May 9, 2022

14 Frequently Asked Java Interview Questions and Answers [2022]Neha Kaushik on May 6, 2022
Join Geekflare Newsletter
Every week we share trending articles and tools in our newsletter. More than 10,000 people enjoy reading, and you will love it too.