Skip to main content
HomeTutorialsPython

How to Use the NumPy linspace() Function

Learn how to use the NumPy linspace() function in this quick and easy tutorial.
Apr 2024

NumPy is an essential package in the Python data science ecosystem, offering a wide array of functions to manipulate numerical data efficiently. Among these, the linspace() function is often used to generate evenly spaced values over a specified interval, making it a useful tool for tasks that require precise numerical ranges, such as data visualization and mathematical modeling. In this tutorial, I’ll show you the ins and outs of the linspace() function.

The Short Answer: How to Use np.linspace()

If you’re in a hurry, here’s the quickest explanation of the linspace() function. NumPy's linspace() function generates an array of evenly spaced numbers over a defined interval. Here, for example, we create an array that starts at 0 and ends at 100, throughout an interval of 5 numbers. As you can expect, it returns an array with [0, 25, 75, 100].

import numpy as np

# Basic usage of linspace to create an array from 0 to 100 with 5 elements
linspace_example = np.linspace(0, 100.0, 5)
linspace_example # Return example

# Output: array([  0.,  25.,  50.,  75., 100.])

Why use NumPy’s linspace() function?

The linspace() function is a simple and efficient method for generating linearly spaced values, offering a useful solution for a variety of scenarios where specific numerical ranges are needed, such as in data visualization, simulations, and even in the fine-tuning of algorithms. Here are a few examples of where linspace() can be used:

  • Data visualization tasks: For example, when creating a line graph to represent the trajectory of a satellite over time, linspace() can be used to generate the time intervals at which the position data is sampled, ensuring a smooth and continuous line on the graph.
  • Simulations: In financial modeling, to assess the impact of varying interest rates on bond pricing, linspace() can produce a range of interest rates from the lowest possible to the highest anticipated, allowing for a comprehensive analysis across the entire spectrum.
  • Scientific research: While studying the effects of global warming on polar ice caps, researchers might use linspace() to create a series of evenly spaced time intervals over several decades. At each interval, they could simulate the average global temperature increase and its impact on ice melt rates.

NumPy linspace() Syntax and Usage with Examples

As mentioned before, the linspace() function creates linearly spaced values which is useful for various numerical computations. Before diving into examples, let’s look at the different arguments you can work with when using linspace().

NumPy linspace() Arguments

  • start: The starting value of the sequence.
  • stop: The end value of the sequence.
  • num (optional): The specified interval. The default is 50, and it must be non-negative.
  • endpoint (optional): If True (default), stop is the last sample. If False, the stop value is not included in the sequence generated by linspace(). This means that the function will create evenly spaced samples within the range from start to just before stop, effectively excluding the stop value itself from the sequence. This can be useful when you need a range that approaches but does not reach the endpoint, allowing for more flexible control over the range of values generated.
  • retstep (optional): If True, returns (samples, step), where step is the spacing between samples.
  • dtype (optional): The type of the output array. If not given, the dtype will be determined by the start and stop arguments.
  • axis (optional): The axis in the result to store the samples, only when working with multi-dimensional arrays.

Creating 1-dimensional arrays with linspace()

Now that we’ve deeply understood the arguments available in linspace(), let’s look at a few examples in action!

Creating an evenly spaced 1-dimensional array using linspace()

This example creates an array of 7 evenly spaced numbers between 0 and 10.

import numpy as np

# Create an array of 7 evenly spaced elements from 0 to 10
uniform_array = np.linspace(0, 10, num=7)
print("Uniform Array")
uniform_array
Uniform Array
array([ 0., 1.66666667, 3.33333333, 5., 6.66666667,8.33333333, 10.])

Excluding the endpoint in an evenly spaced 1-dimensional array using linspace()

In this instance, we generate an array of 8 numbers between 10 and 20, but exclude the final value (20) from the array, showcasing the endpoint argument in action.

import numpy as np


# Create an array of 8 elements from 10 to 20, excluding 20
exclude_final_array = np.linspace(10, 20, num=8, endpoint=False)
print("Array Excluding Final Value")
exclude_final_array
Array Excluding Final Value
array([10. , 11.25, 12.5 , 13.75, 15. , 16.25, 17.5 , 18.75])

Including the step size in an evenly spaced 1-dimensional array using linspace()

Here, we create an array of 4 elements between -5 and 5. We also capture and display the step size.

import numpy as np


# Create an array of 4 elements from -5 to 5 and capture the step size
step_array, step = np.linspace(-5, 5, num=4, retstep=True)
print("Array with Defined Step Size", step_array)
print("Step Size", step)
Array with Defined Step Size [-5.         -1.66666667  1.66666667  5.        ]
Step Size 3.3333333333333335

Creating N-dimensional arrays with linspace()

linspace() is also useful for generating multi-dimensional arrays. Here, we show a few examples of that in action.

Generating a 2-dimensional array using linspace()

This example illustrates how to generate a 2D array where each row transitions smoothly from the vector [0, 10] to [5, 15], creating a gradient effect over 4 steps.

import numpy as np


# Perform column-wise linear interpolation from [10, 20] to [15, 25] over 3 steps
column_interpolation_array = np.linspace([10, 20], [15, 25], num=3, axis=1)
print("Column-wise Interpolation Array:")
print(column_interpolation_array)
Column-wise Interpolation Array:
[[10.  12.5 15. ]
 [20.  22.5 25. ]]

Alternatives to NumPy linspace()

While linspace() is highly useful, there are alternatives worth considering, like NumPy's arange() function and list comprehensions.

Using the NumPy arange() function

The arange() function generates values within a given interval. Unlike linspace(), the spacing between values is specified rather than the number of values.

# Using arange to generate values from 0 to 10, spaced by 2
arange_example = np.arange(0, 10, 2)
arange_example

# Returns array([0, 2, 4, 6, 8])

# Using linspace() to generate values from 0 to 10, with interval set to 2
linspace_example = np.linspace(0, 10, 2)
linspace_example

# Returns array([0.,10.0])

Using list comprehensions

List comprehensions provide a more Pythonic way of generating lists, though they lack the vectorization benefits and flexibility of NumPy linspace().

list_comp = [x for x in range(10)]
print(list_comp)

# Outputs [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

Final Thoughts

NumPy's linspace() function is a fundamental tool in the data science toolkit, offering precision and flexibility in generating numerical sequences. If you want to strengthen your NumPy chops, check out this tutorial on NumPy Arrays, this NumPy Cheat Sheet, or consider enrolling in our Introduction to NumPy course.


Photo of Adel Nehme
Author
Adel Nehme

Adel is a Data Science educator, speaker, and Evangelist at DataCamp where he has released various courses and live training on data analysis, machine learning, and data engineering. He is passionate about spreading data skills and data literacy throughout organizations and the intersection of technology and society. He has an MSc in Data Science and Business Analytics. In his free time, you can find him hanging out with his cat Louis.

Topics

Continue Your NumPy Learning Journey Today!

Course

Introduction to NumPy

4 hr
34.8K
Master your skills in NumPy by learning how to create, sort, filter, and update arrays using NYC’s tree census.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

blog

Intermediate Python for Data Science: Matplotlib

Learn to visualize real data with matplotlib's functions.
Karlijn Willems's photo

Karlijn Willems

11 min

tutorial

Python Range() Function Tutorial

Learn about the Python Range() function and its capabilities with the help of examples.
Aditya Sharma's photo

Aditya Sharma

7 min

tutorial

Python Numpy Array Tutorial

A NumPy tutorial for beginners in which you'll learn how to create a NumPy array, use broadcasting, access values, manipulate arrays, and much more.
Karlijn Willems's photo

Karlijn Willems

45 min

tutorial

Python Arrays

Python arrays with code examples. Learn how to create and print arrays using Python NumPy today!
DataCamp Team's photo

DataCamp Team

3 min

tutorial

Scipy Tutorial: Vectors and Arrays (Linear Algebra)

A SciPy tutorial in which you'll learn the basics of linear algebra that you need for machine learning in Python, with a focus how to with NumPy.
Karlijn Willems's photo

Karlijn Willems

28 min

tutorial

String Split in Python Tutorial

Learn how you can perform various operations on string using built-in Python functions like split, join and regular expressions.
DataCamp Team's photo

DataCamp Team

2 min

See MoreSee More