12

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]

lmiguelvargasf
  • 63,191
  • 45
  • 217
  • 228
efirvida
  • 4,592
  • 3
  • 42
  • 68
  • 3
    use the `range` function – lmiguelvargasf Jun 30 '15 at 16:37
  • 4
    In the likely event that you're using `numpy`, there's a similar `arange`; note that `range` and `arange` are both half-open, they **exclude the `stop`** (e.g. `np.arange(1, 10, 0.5)` will be `array([ 1. , 1.5, 2. , ... , 8.5, 9. , 9.5])`). – jonrsharpe Jun 30 '15 at 16:38
  • range didn't work with floating increment, if i use np.arange, then how to include the increment after? – efirvida Jun 30 '15 at 17:25

4 Answers4

8

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

Glorfindel
  • 21,988
  • 13
  • 81
  • 109
hitzg
  • 12,133
  • 52
  • 54
6

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]
Bi Rico
  • 25,283
  • 3
  • 52
  • 75
  • miss parenthesis on `print(np.linspace(1, 3, num=5)` may be `print(np.linspace(1, 3, num=5))` but thanks!!! +1. i solve my problem using `np.append(np.arange(start, stop, step),stop)` – efirvida Jun 30 '15 at 18:04
2
import numpy as np
a = np.arange(1, 10, 0.5)
print (a)
Adolfo Correa
  • 813
  • 8
  • 17
0

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

xrange(start, stop, step)

But xrange cannot do floats.

Kellen
  • 581
  • 5
  • 18
  • You can with the proper workaround: http://stackoverflow.com/questions/477486/python-decimal-range-step-value .. however, `numpy.arange` is more elegant. – rayryeng Jul 20 '15 at 15:37