Python:NumPy .linspace()
The .linspace() function in NumPy creates an array of evenly spaced numbers over a specified interval. Unlike other sequence-generating functions such as .arange(), .linspace() allows specifying the exact number of points needed in the array, and NumPy will automatically calculate the spacing between the values. This makes it particularly useful for generating sample points for mathematical functions, creating coordinate grids for plotting, and designing evenly spaced numerical sequences for scientific computing.
The function is commonly used in data visualization, signal processing, numerical integration, and mathematical modelling where precise control over the number of samples in an interval is needed. It’s especially valuable when working with functions that need to be evaluated at regular intervals, or when creating axes for plots that require a specific number of data points.
Syntax
numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0)
Parameters:
start: The starting value of the sequence.stop: The end value of the sequence.num(optional): Number of samples to generate. Default is50.endpoint(optional): IfTrue(default), stop is the last sample. Otherwise, it is not included.retstep(optional): IfTrue, returns (samples, step), where step is the spacing between samples.dtype(optional): The type of the output array. If not given, the data type is inferred from start and stop.axis(optional): The axis in the result to store the samples. Relevant only if start or stop are array-like.
Return value:
- Returns a numpy ndarray of evenly spaced samples. If
retstepis True, it also returns the step size between samples.
Example 1: Basic Usage of .linspace()
This example shows how to create a simple array of evenly spaced numbers using the .linspace() function:
import numpy as np# Create an array of 5 values evenly spaced from 0 to 1array = np.linspace(0, 1, 5)# Print the arrayprint("Evenly spaced array:")print(array)# Calculate the step size manually to verifystep_size = (1 - 0) / (5 - 1)print(f"Manually calculated step size: {step_size}")# Alternatively, get the step size directly using retsteparray, step = np.linspace(0, 1, 5, retstep=True)print(f"Step size returned by linspace: {step}")
The output generated by this code will be:
Evenly spaced array:[0. 0.25 0.5 0.75 1. ]Manually calculated step size: 0.25Step size returned by linspace: 0.25
This example demonstrates how to create an array of 5 evenly spaced values from 0 to 1. The step size is 0.25, which we verify both by manual calculation and by using the retstep parameter.
Example 2: Plotting a Sine Wave using .linspace()
This example demonstrates how to use .linspace() to create x-coordinates for plotting a sine wave:
import numpy as npimport matplotlib.pyplot as plt# Create x values from 0 to 2π with 100 pointsx = np.linspace(0, 2 * np.pi, 100)# Calculate sine values for each xy = np.sin(x)# Plot the sine waveplt.figure(figsize=(10, 5))plt.plot(x, y)plt.title('Sine Wave')plt.xlabel('x')plt.ylabel('sin(x)')plt.grid(True)plt.axhline(y=0, color='k', linestyle='-', alpha=0.3)plt.axvline(x=0, color='k', linestyle='-', alpha=0.3)# Show the plotplt.show()# Print a few sample points to illustrate the even spacingprint("First 5 x values:", x[:5])print("Corresponding y values:", y[:5])
The output of the above code will be:

First 5 x values: [0. 0.06346652 0.12693304 0.19039955 0.25386607]Corresponding y values: [0. 0.06342392 0.12655467 0.18930021 0.25157326]
This example shows how .linspace() is used in data visualization to create evenly spaced points for plotting a mathematical function. The x-axis values are generated with .linspace() to ensure an even distribution of points over the domain, which results in a smooth curve.
Codebyte Example: Creating a Temperature Gradient Simulation
This example demonstrates how to use .linspace() for a practical application - simulating temperature distribution along a metal rod:
This example illustrates a practical application of .linspace() in scientific modeling. We create evenly spaced measurement points along a rod and model a linear temperature gradient. The use of .linspace() ensures that our measurement points are uniformly distributed, which is crucial for accurate simulation and visualization of physical phenomena.
Frequently Asked Questions
1. What’s the difference between np.linspace() and np.arange()?
While both functions create sequences of numbers, np.linspace() lets you specify the number of points and generates evenly spaced values, whereas np.arange() requires a step size. .linspace() is generally preferred for floating-point ranges as it avoids rounding errors that can accumulate when using .arange() with decimal steps.
2. What is the difference between NumPy .linspace() and .logspace()?
NumPy .linspace() creates values evenly spaced on a linear scale, while .logspace() creates values evenly spaced on a logarithmic scale. .logspace() generates points between 10^start and 10^stop, making it ideal for data spanning multiple orders of magnitude or for logarithmic plots.
3. Can .linspace() generate logarithmic sequences?
No, .linspace() generates linearly spaced sequences. For logarithmic sequences, use np.logspace() which creates numbers evenly spaced on a log scale.
4. How do I exclude the endpoint in .linspace()?
Set the endpoint parameter to False: np.linspace(start, stop, num, endpoint=False)
5. Is there a multidimensional version of .linspace()?
Yes, you can create multidimensional arrays by reshaping the output or using meshgrid with linspace. For example:
x = np.linspace(0, 1, 10)y = np.linspace(0, 1, 10)X, Y = np.meshgrid(x, y) # Creates a 2D grid
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn Python:NumPy on Codecademy
- Machine Learning Data Scientists solve problems at scale, make predictions, find patterns, and more! They use Python, SQL, and algorithms.
- Includes 27 Courses
- With Professional Certification
- Beginner Friendly.95 hours
- Learn the basics of Python 3.12, one of the most powerful, versatile, and in-demand programming languages today.
- With Certificate
- Beginner Friendly.24 hours