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 includestopin 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
| Parameter | Description | Default |
|---|---|---|
| start | Start of interval | Required |
| stop | End of interval | Required |
| num | Number of samples to generate | 50 |
| endpoint | Include stop in output | True |
| retstep | Return step size with samples | False |
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.