Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use numpy.linspace(start, stop, num) when you know how many evenly spaced values you need. By default, it includes both endpoints; set endpoint=False to leave out the stop value. For example, np.linspace(2.0, 3.0, 5) returns five values from 2.0 through 3.0, spaced by 0.25.

Basic use: choose the number of samples

NumPy describes linspace as returning evenly spaced numbers over a specified interval. Its documented signature is numpy.linspace(start, stop, num=50, endpoint=True, retstep=False, dtype=None, axis=0, device=None). The default is 50 samples, including the stop value. NumPy 2.0 linspace reference.

import numpy as np

x = np.linspace(2.0, 3.0, num=5)
print(x)
# [2.   2.25 2.5  2.75 3.  ]

The interval length is 1.0 and there are four gaps between five samples, so each gap is 0.25. In general, with the default closed interval and at least two samples, the spacing is (stop - start) / (num - 1). The formula describes the spacing, not a promise that every decimal will have an exact binary floating-point representation.

Install NumPy if needed with python -m pip install numpy, then run the example in a Python file or notebook. Import it using the conventional alias np.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Include or exclude the endpoint

By default, endpoint=True includes stop, giving a closed interval [start, stop]. Set endpoint=False for a half-open interval [start, stop); the start remains included, but the stop is not. Since the same number of samples is distributed across a different interval rule, the spacing changes.

closed = np.linspace(2.0, 3.0, num=5)
# [2.   2.25 2.5  2.75 3.  ]

half_open = np.linspace(2.0, 3.0, num=5, endpoint=False)
# [2.  2.2 2.4 2.6 2.8]

In the closed example, five samples make four gaps of 0.25. In the half-open example, five samples span the distance from 2.0 up to but not including 3.0, producing a spacing of 0.2. This option is useful when the endpoint would duplicate a boundary value, such as when generating samples around a cycle.

Get the step size with retstep

Set retstep=True when you want the values and NumPy’s calculated spacing from the same call. The return value becomes a pair: the sample array and the step.

samples, step = np.linspace(2.0, 3.0, num=5, retstep=True)
print(samples)
# [2.   2.25 2.5  2.75 3.  ]
print(step)
# 0.25

Without retstep=True, the function returns only the array. For array-valued endpoints, the returned step can also be array-shaped, reflecting the corresponding ranges.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Parameters and output details

Parameter What it controls Practical detail
start, stop Interval endpoints; each may be a scalar or array-like. Array endpoints can describe multiple ranges, subject to broadcasting rules.
num Number of samples; default is 50. Must be non-negative. It counts returned values, not gaps.
endpoint Whether to include stop; default is True. Changing it changes the spacing for the same sample count.
retstep Whether to return the spacing along with the array. When true, unpack the result into two values.
dtype Explicit output dtype. Without it, integer-looking endpoints produce floating-point output rather than an integer array.
axis Position of the sample dimension when endpoints are array-like. 0 inserts the dimension first; -1 puts it last.
device Device selection for Array-API interoperability. The current documented implementation accepts "cpu".

These parameters are documented in the NumPy 2.0 API reference. Unless you request a dtype, NumPy infers an appropriate numeric dtype; it does not make integer output merely because the endpoints are whole numbers.

Integer dtype: understand the rounding rule

You can explicitly request an integer dtype, but this changes the values when the evenly spaced results are not integers. Since NumPy 1.20.0, values requested with an integer dtype are rounded toward negative infinity. That is floor-style rounding, including for negative values. NumPy’s version notes.

values = np.linspace(-2, 2, num=5, dtype=int)
print(values)
# [-2 -1  0  1  2]

For fractional values, inspect the floating-point sequence first if rounding affects your calculation. To reproduce the older truncation-toward-zero behavior, generate the floating-point array and then convert it:

truncated = np.linspace(start, stop, num=5).astype(int)

Truncation and rounding down differ for negative fractions: truncating -1.8 gives -1, while rounding toward negative infinity gives -2. Choose based on the mathematical behavior you need, not just the desired storage type.

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Generate several ranges with array endpoints

start and stop may be arrays. NumPy broadcasts them together, then inserts the sampling dimension at axis. This lets one call generate coordinated ranges; check the shapes of your endpoints and output rather than assuming the samples will be in a particular orientation.

starts = np.array([0.0, 10.0])
stops = np.array([1.0, 20.0])

ranges = np.linspace(starts, stops, num=3, axis=0)
print(ranges.shape)
# (3, 2)
print(ranges)
# [[ 0.   10. ]
#  [ 0.5  15. ]
#  [ 1.   20. ]]

Here the two endpoint pairs define two ranges, each with three samples. The default axis=0 puts the three-sample dimension first, producing shape (3, 2). Use axis=-1 to place the sample dimension last, which would produce shape (2, 3) for these endpoints. In more complex cases, NumPy’s broadcasting rules determine whether endpoint shapes are compatible. The API reference covers array endpoints and axis placement.

Choose linspace, arange, geomspace, or logspace

Function You specify Spacing and endpoints Good fit
linspace Number of samples. Linear spacing; includes the endpoint by default, with an option to exclude it. You need a fixed count or explicit control over endpoint inclusion.
arange Step size. Linear increments; floating-point lengths and effective steps can be unstable. The increment is central and the range is suitable for step-based generation.
geomspace Direct start and stop values. Geometric progression, rather than equal additive gaps. You need logarithmic-style spacing between endpoint values.
logspace Start and stop exponents, plus a base. Logarithmically spaced values formed from exponents. You want values such as powers of a base across an exponent interval.

Use linspace when the count matters more than the increment. Use arange when you know the desired step; NumPy warns that floating-point steps can make the resulting length and effective step unstable, and points to linspace for such cases. For multiplicative spacing, choose geomspace when you have the endpoint values or logspace when you have the exponents. NumPy arange reference; NumPy linspace reference.

Common errors and troubleshooting

  • Unexpected number of values: num is a count, not a step. Specify the count you need; for a step-driven range, consider arange, keeping its floating-point cautions in mind.
  • The stop value is missing: Check whether you set endpoint=False. Set it to True or omit it to use the default.
  • The interval is divided into an unexpected number of gaps: For an included endpoint there are num - 1 gaps when there are at least two samples. For an excluded endpoint, the spacing is different; do not reuse the closed-interval formula.
  • Integer values differ from expectations: An explicit integer dtype rounds toward negative infinity in current NumPy behavior. Generate floats and call .astype(int) if truncation toward zero is what you intend.
  • Array endpoint shapes do not work: Confirm that start and stop broadcast together. Then set axis to put the sample dimension where later operations expect it.
  • You tried device="gpu": The documented device argument for this Array-API interoperability use accepts only "cpu".
  • You asked for zero samples: num may be non-negative, but a zero count produces no sample values. Use a positive count if you need a usable sequence; handle zero explicitly if it is a valid input to your program.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Performance and numerical reliability

linspace allocates an array containing the requested samples, so memory use grows with the number of returned values and the dtype. Avoid requesting an unnecessarily large array if downstream code can work in chunks or compute values as needed. If a particular decimal increment is essential, remember that floating-point values may be approximations; use an appropriate numeric representation for the precision requirements of your application.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

For reproducible interval shape, specifying num makes the output length explicit. For reproducible spacing, also set endpoint deliberately rather than relying on an implicit choice. When output shape or type is important, state axis and dtype explicitly and test those properties.

Or skip the browser setup

This NumPy task does not require browser automation. For developers who also need website captures, ScreenshotNeo is a screenshot API and MCP server; it returns an image or PDF from a single request. For example, with a ScreenshotNeo API key:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

See the ScreenshotNeo API documentation for request options. ScreenshotNeo accepts cookie or consent banners and removes more than 60 known consent platforms, newsletter popups, and chat widgets before capture; each step can be turned off. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed. Its MCP server offers take_screenshot, get_page_info, and capture_pdf tools for AI agents. The free plan includes 1,000 screenshots a month without a card; paid plans start at $5 for 3,000 shots. Sign up free for ScreenshotNeo.

Frequently Asked Questions

What happens when num is 1?

The call returns one sample rather than a multi-point sequence. If your calculation depends on how the interval is represented in this case, check the returned result directly.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Can linspace create values in descending order?

Yes. Use a start value greater than the stop value; the samples are evenly spaced in the descending direction.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.