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:

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


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:

Answered By – hitzg

Answer Checked By – Mary Flores (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.