[Numpy-discussion] Why does fancy indexing work like this?

Aaron Meurer asmeurer at gmail.com
Wed Jul 22 18:23:13 EDT 2020


Why does fancy indexing have this behavior?

>>> a = np.empty((0, 1, 2))
>>> b = np.empty((1, 1, 2))
>>> a[np.array([10, 10])]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: index 10 is out of bounds for axis 0 with size 0
>>> a[:, np.array([10, 10])]
array([], shape=(0, 2, 2), dtype=float64)
>>> a[:, :, np.array([10, 10])]
array([], shape=(0, 1, 2), dtype=float64)
>>> b[np.array([10, 10])]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: index 10 is out of bounds for axis 0 with size 1
>>> b[:, np.array([10, 10])]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: index 10 is out of bounds for axis 1 with size 1
>>> b[:, :, np.array([10, 10])]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
IndexError: index 10 is out of bounds for axis 2 with size 2

As far as I can tell, the behavior is that if an array has a 0
dimension and an integer array index indexes an axis that isn't 0,
there are no bounds checks. Why does it do this? It seems to be
inconsistent with the behavior of shape () fancy indices (integer
indices). I couldn't find any reference to this behavior in
https://numpy.org/doc/stable/reference/arrays.indexing.html.

Aaron Meurer


More information about the NumPy-Discussion mailing list