Search code examples
pythonmatlabrange

How to create range of numbers in Python like in MATLAB


Is there any way to create a range of numbers in Python like MATLAB using a simple syntax, i.e, not using loops. For example:

MATLAB: a = 1:0.5:10 give a = [1 1.5 2 2.5 3 3.5 .... 9.5 10]


Solution

  • As others have pointed out, np.arange gets you closest to what you are used to from matlab. However, np.arange excludes the end point. The solution that you proposed in your own answer can lead to wrong results (see my comment).

    This however, will always work:

    start = 0
    stop = 3
    step = 0.5
    a = np.arange(start, stop+step, step)
    

    For further reading: Especially if you are an experienced matlab-user, this guide/cheat sheet might be interesting: Link