The easiest way to implement this is a generator function:

Use with AIfrom __future__ import division

def linspace(start, stop, n):
    if n == 1:
        yield stop
        return
    h = (stop - start) / (n - 1)
    for i in range(n):
        yield start + h * i

Example usage:

Use with AI>>> list(linspace(1, 3, 5))
[1.0, 1.5, 2.0, 2.5, 3.0]

That said, you should definitely consider using NumPy, which provides the numpy.linspace() function and lots of other features to conveniently work with numerical arrays.

Answer from Sven Marnach on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › alternatives to numpy logspace and linspace?
Alternatives to Numpy logspace and linspace? : r/learnpython
March 14, 2016 - Not necessarily. If you are going to do python for loops, using numpy arrays is usually slower unless numpy is doing some really heavy math to calculate the array.
🌐
GitHub
gist.github.com › pmav99 › d124872c879f3e9fa51e
Pure python linspace / logspace implementation · GitHub
Pure python linspace / logspace implementation · Raw · linspace.py · This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Find elsewhere
🌐
Real Python
realpython.com › np-linspace-numpy
np.linspace(): Create Evenly or Non-Evenly Spaced Arrays – Real Python
July 3, 2026 - However, even using a list comprehension is rather clumsy and inelegant compared to using np.linspace(). You first need to work out the interval required and then use that interval within a loop. In most applications, you’ll still need to convert the list into a NumPy array since element-wise computations are less complicated to perform using NumPy arrays. Another point you may need to take into account when deciding whether to use NumPy tools or core Python is execution speed.
🌐
Stack Overflow
stackoverflow.com › questions › 73659121 › linspace-in-python
matlab - Linspace in Python? - Stack Overflow
Typing "python linspace" in google gives you the answer....... ... Save this answer. ... Show activity on this post. As Bylal said it's a numpy thing. Numpy mostly exists for greater easy of use and performance in mathematical functions.
🌐
Finxter
blog.finxter.com › home › learn python blog › how to create a sequence of evenly spaced values [vanilla python & numpy linspace]
How to Create a Sequence of Evenly Spaced Values [Vanilla Python & Numpy Linspace] - Be on the Right Side of Change
January 21, 2021 - print([int(x) for x in np.linspace(start, stop, num_vals)]) # [10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] ... Numpy is a popular Python library for data science focusing on linear algebra.
🌐
DataCamp
datacamp.com › home › tutorials › python › how to use the numpy linspace() function
How to Use the NumPy linspace() Function | DataCamp
April 5, 2024 - If you’re in a hurry, here’s the quickest explanation of the linspace() function. NumPy's linspace() function generates an array of evenly spaced numbers over a defined interval. Here, for example, we create an array that starts at 0 and ends at 100, throughout an interval of 5 numbers.
🌐
GeeksforGeeks
geeksforgeeks.org › numpy-linspace
NumPy linspace() Method | Create Evenly Spaced Array - GeeksforGeeks
January 24, 2025 - Unlike the range() function in Python that generates numbers with a specific step size. linspace() allows you to specify the total number of points you want in the array, and NumPy will calculate the spaci
🌐
Reddit
reddit.com › r/julia › how do you do the equivalent of linspace?
r/Julia on Reddit: How do you do the equivalent of linspace?
January 31, 2021 -

I have to do a lot of plotting and I always make it such that if I have to vary some parameter everything else adjusts accordingly, but sometimes when I change parameters there's issue with the number of elements in lists which prevents me from plotting along with a whole bunch of other things. (right now I'm using a:0.01:b)

So how do I get a list of n evenly spaced elements from a to b like in

np.linspace(a,b,n)

???

🌐
GeeksforGeeks
geeksforgeeks.org › python › numpy-linspace
NumPy linspace() Method | Create Evenly Spaced Array - GeeksforGeeks
February 14, 2026 - By default, numpy.linspace() includes the stop value as the last element of the array. This behavior can be changed using the endpoint parameter.
Top answer
1 of 1
6

I'm surprised that I can't find a similar Q&A on Stack Overflow. There are a few on doing something similar for random numbers from a discrete distribution, but not for continuous distributions and also not as a modified np.arange or np.linspace.

If you need to get an x range for plotting that has finer sampling in areas where you expect the function to fluctuate more rapidly, you can create a nonlinear function that takes inputs in the range 0 to 1 and produces outputs in the same range that proceeds nonlinearly. For example:

Use with AIdef f(x):
    return x**2

angles = 2*np.pi*f(np.linspace(0, 1, num, endpoint=False))

This will produce fine sampling near zero and coarse sampling near 2*pi. For more fine-grained control of the sampling density, you can use the function below. As a bonus, it will also allow random sampling.

Use with AIimport numpy as np

def density_space(xs, ps, n, endpoint=False, order=1, random=False):
    """Draw samples with spacing specified by a density function.

    Copyright Han-Kwang Nienhuys (2020).
    License: any of: CC-BY, CC-BY-SA, BSD, LGPL, GPL.
    Reference: https://stackoverflow.com/a/62740029/6228891
    
    Parameters:
        
    - xs: array, ordered by increasing values.
    - ps: array, corresponding densities (not normalized).
    - n: number of output values.
    - endpoint: whether to include x[-1] in the output.
    - order: interpolation order (1 or 2). Order 2 will
      require dense sampling and a smoothly varying density 
      to work correctly.
    - random: whether to return random samples, ignoring endpoint).
      in this case, n can be a shape tuple.

    Return:
        
    - array, shape (n,), with values from xs[0] to xs[-1]
    """
    from scipy.interpolate import interp1d
    from scipy.integrate import cumtrapz
    
    cps = cumtrapz(ps, xs, initial=0)
    cps *= (1/cps[-1])
    intfunc = interp1d(cps, xs, kind=order)
    if random:
        return intfunc(np.random.uniform(size=n))
    else:
        return intfunc(np.linspace(0, 1, n, endpoint=endpoint))

Test:

Use with AIvalues = density_space(
    [0, 100, 101, 200],
    [1, 1, 2, 2],
    n=12, endpoint=True)

print(np.around(values))

[  0.  27.  54.  82. 105. 118. 132. 146. 159. 173. 186. 200.]

The cumulative density function is created using trapezoid integration, which is essentially based on linear interpolation. A higher-order integration is not safe because the input may have (near-)discontinuities, like the jump from x=100 to x=101 in the example. A discontinuity in the input results in a discontinuous first derivative in the cumulative density function (cps in the code), which will cause problems with a smooth interpolation (order 2 or above). Hence the recommendation to use order=2 only for a smooth density function - and not to use any higher orders.

🌐
Expert Python
expertpython.fr › lexique › linspace()
linspace() - Expert Python
La fonction linspace() est couramment utilisée pour générer des tableaux de nombres uniformément espacés sur un intervalle spécifié.
🌐
YouTube
youtube.com › watch
Graphing in Python with the linspace() Function - YouTube
As part of a series on Python list operations, plotting and drawing, this NCLab video demonstrates how to set intervals on a graph, build x arrays, and draw ...
Published: September 13, 2018
🌐
GeeksforGeeks
geeksforgeeks.org › numpy-linspace-python
numpy.linspace() in Python - GeeksforGeeks
May 19, 2022 - The numpy.linspace() function returns number spaces evenly w.r.t interval. Similar to numpy.arange() function but instead of step it uses sample number.