Unlike np.arange(), which you specify by step size, np.linspace(start, stop, num) lets you specify exactly how many points you want, and NumPy calculates the appropriate spacing between them, which avoids the floating-point step-count uncertainty that np.arange() can have with fractional steps. By default the stop value is included as the last point; passing endpoint=False excludes it, which is useful for periodic data, like angles from 0 up to but not including a full circle, where including both endpoints would duplicate a point.
1Understanding np.linspace()
Unlike np.arange(), which you specify by step size, np.linspace(start, stop, num) lets you specify exactly how many points you want, and NumPy calculates the appropriate spacing between them, which avoids the floating-point step-count uncertainty that np.arange() can have with fractional steps. By default the stop value is included as the last point; passing endpoint=False excludes it, which is useful for periodic data, like angles from 0 up to but not including a full circle, where including both endpoints would duplicate a point.
Reach for np.linspace() instead of np.arange() whenever you specifically care about the exact number of points generated, like for plotting a smooth curve with exactly 100 points, rather than the exact step size between them.
import numpy as np
arr = np.linspace(0, 1, 5)
print(arr)2Practical Example
Here is a real-world application of np.linspace() showing how it is used in production NumPy code.
import numpy as np
angles = np.linspace(0, 2 * np.pi, 4, endpoint=False)
print(angles)3Best Practices
Follow these guidelines when working with np.linspace():
1. Use np.linspace() instead of np.arange() when the number of points matters more than the exact step size, especially for float ranges
2. Set endpoint=False for periodic ranges, like angles around a circle, to avoid an unwanted duplicate point at the wraparound
3. Pass retstep=True when you also need to know the computed step size that np.linspace() used
Tip: Reach for np.linspace() instead of np.arange() whenever you specifically care about the exact number of points generated, like for plotting a smooth curve with exactly 100 points, rather than the exact step size between them.
import numpy as np
arr = np.linspace(0, 1, 5)
print(arr)