From the previous SO we learn that the 'a' stands, in some sense, for 'array'. arange
is a function that returns a numpy array that is similar, at least in simple cases, to the list produced by list(range(...))
. From the official arange
docs:
For integer arguments the function is roughly equivalent to the Python built-in range, but returns an ndarray rather than a range instance.
In [104]: list(range(-3,10,2))
Out[104]: [-3, -1, 1, 3, 5, 7, 9]
In [105]: np.arange(-3,10,2)
Out[105]: array([-3, -1, 1, 3, 5, 7, 9])
In py3, range
by itself is "unevaluated", it's generator like. It's the equivalent of the py2 xrange
.
The best "definition" is the official documentation page:
https://numpy.org/doc/stable/reference/generated/numpy.arange.html
But maybe you are wondering when to use one or the other. The simple answer is - if you are doing python level iteration, range
is usually better. If you need an array, use arange
(or np.linspace
as suggested by the docs).
In [106]: [x**2 for x in range(5)]
Out[106]: [0, 1, 4, 9, 16]
In [107]: np.arange(5)**2
Out[107]: array([ 0, 1, 4, 9, 16])
I often use arange
to create a example array, as in:
In [108]: np.arange(12).reshape(3,4)
Out[108]:
array([[ 0, 1, 2, 3],
[ 4, 5, 6, 7],
[ 8, 9, 10, 11]])
While it is possible to make an array from a range
, e.g. np.array(range(5))
, that is relatively slow. np.fromiter(range(5),int)
is faster, but still not as good as the direct np.arange
.