linspace() (NumPy)

np.linspace() returns a 1-D array of evenly spaced numbers over a closed interval, where you specify how many points you want rather than the step size. By default it includes both endpoints.

NumPy

linspace(start, stop, num) gives exactly num values from start to stop inclusive, computing the spacing for you. This makes it the right choice over arange when the count matters — sampling a function at 100 points, or building axis ticks — because it always hits the endpoints exactly.

Set endpoint=False to exclude the final value (useful for periodic data), and retstep=True to also get the spacing back. The spacing is computed in floating point, so the result is clean even when the step would be an awkward fraction.

Use linspace when you know how many samples you want and arange when you know the step between them.

Syntax

np.linspace(start, stop, num=50, endpoint=True)

Examples

Python

import numpy as np
print(np.linspace(0, 1, 5))

Output:

[0.   0.25 0.5  0.75 1.  ]

Learn it in a lesson

See also

Back to the Dictionary