How to create range of numbers in Python like in MATLAB

Question:

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]

Asked By: efirvida

||

Answers:

import numpy as np
a = np.arange(1, 10, 0.5)
print (a)
Answered By: Adolfo Correa

Python’s built in xrange function can generate integers like so:

xrange(start, stop, step)

But xrange cannot do floats.

Answered By: Kellen

Numpy has arange and r_ which look something like this:

import numpy as np
print(np.arange(1, 3, .5))
# [ 1.   1.5  2.   2.5]
print(np.r_[1:3:.5])
# [ 1.   1.5  2.   2.5]

Notice that it is a little different than matlab, first the order of the stop and step are reversed in numpy compared to matlab, and second the stop is not included the the result. You might also consider using linspace it’s often preferred over arange when you’re working with floating point numbers because num can be defined more precisely than step:

print(np.linspace(1, 3, num=5))
# [ 1.   1.5  2.   2.5  3. ]

or

print(np.linspace(1, 3, num=4, endpoint=False))
# [ 1.   1.5  2.   2.5]
Answered By: Bi Rico

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

Answered By: hitzg
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.