0
0
NumpyHow-ToBeginner ยท 3 min read

How to Use np.linspace in NumPy for Evenly Spaced Numbers

Use np.linspace(start, stop, num) to create an array of num evenly spaced numbers from start to stop. It is useful for generating sequences where you want equal intervals between points.
๐Ÿ“

Syntax

The basic syntax of np.linspace is:

  • start: The first number in the sequence.
  • stop: The last number in the sequence.
  • num: How many numbers to generate (default is 50).
  • endpoint: Whether to include stop in the output (default is True).
  • retstep: If True, also return the spacing between numbers.
python
np.linspace(start, stop, num=50, endpoint=True, retstep=False)
๐Ÿ’ป

Example

This example creates 5 evenly spaced numbers from 0 to 10, including 10.

python
import numpy as np

numbers = np.linspace(0, 10, 5)
print(numbers)
Output
[ 0. 2.5 5. 7.5 10. ]
โš ๏ธ

Common Pitfalls

One common mistake is forgetting that np.linspace includes the stop value by default. If you want to exclude it, set endpoint=False. Also, confusing num with step size can cause unexpected results because num is the count of points, not the gap size.

python
import numpy as np

# Wrong: expecting step size 2 but using num=2
wrong = np.linspace(0, 10, 2)

# Right: use num to control points, not step size
right = np.linspace(0, 10, 6)  # 6 points including 0 and 10

print("Wrong:", wrong)
print("Right:", right)
Output
Wrong: [ 0. 10.] Right: [ 0. 2. 4. 6. 8. 10.]
๐Ÿ“Š

Quick Reference

ParameterDescriptionDefault
startStart of intervalRequired
stopEnd of intervalRequired
numNumber of samples to generate50
endpointInclude stop in outputTrue
retstepReturn step size with samplesFalse
โœ…

Key Takeaways

Use np.linspace to generate a fixed number of evenly spaced points between two values.
The stop value is included by default; set endpoint=False to exclude it.
The num parameter controls how many points, not the step size.
Set retstep=True to get the spacing between points along with the array.
np.linspace is useful for plotting and creating smooth ranges of values.