I've seen it once or twice before, but I can't seem to find any official docs on it: Using python range objects as indices in numpy.
import numpy as np
a = np.arange(9).reshape(3,3)
a[range(3), range(2,-1,-1)]
# array([2, 4, 6])
Let's trigger an index error just to confirm that ranges are not in the official range (pun intended) of legal indexing methods:
a['x']
# Traceback (most recent call last):
# File "<stdin>", line 1, in <module>
# IndexError: only integers, slices (`:`), ellipsis (`...`), numpy.newaxis (`None`) and integer or boolean arrays are valid indices
Now, a slight divergence between numpy and its docs is not entirely unheard of and does not necessarily indicate that a feature is not intended (see for example here).
So, does anybody know why this works at all? And if it is an intended feature what are the exact semantics / what is it good for? And are there any ND generalizations?
range(3)is a list of integers, which numpy treats as "array-like". It would have been a mess if numpy didn't also handle that in a backwards compatible way in Python 3.(...) a non-tuple sequence object(although anon-tuple sequence (such as a list) containing slice objectswill trigger basic indexing, it seems). Not sure why it should hang ifIndexErroris not raised though, but whatever. I think you could make this an answer.np.asarray(x)with works with bothrange(3)and[0,1,2]. Other things produce errors or object dtype arrays. @WarrenWeckesser, makes a good point about compatibility with Py2's version ofrange.