[Numpy-discussion] Inconsistent/unexpected indexing semantics

Sebastian Berg sebastian at sipsolutions.net
Mon Nov 30 15:19:45 EST 2015


On Mo, 2015-11-30 at 18:42 +0100, Lluís Vilanova wrote:
> Hi,
> 
> TL;DR: There's a pending pull request deprecating some behaviour I find
>        unexpected. Does anyone object?
> 
> Some time ago I noticed that numpy yields unexpected results in some very
> specific cases. An array can be used to index multiple elements of a single
> dimension:
> 
>     >>> a = np.arange(8).reshape((2,2,2))
>     >>> a[ np.array([[0], [0]]) ]
>     array([[[[0, 1],
>              [2, 3]]],
>            [[[0, 1],
>              [2, 3]]]])
> 
> Nonetheless, if a list is used instead, it is (unexpectedly) transformed into a
> tuple, resulting in indexing across multiple dimensions:
> 
>     >>> a[ [[0], [0]] ]
>     array([[0, 1]])
> 
> I.e., it is interpeted as:
> 
>     >>> a[ [0], [0] ]
>     array([[0, 1]])
> 
> Or what is the same:
> 
>     >>> a[( [0], [0] )]
>     array([[0, 1]])
> 
> 
> I've been informed that there's a pending pull request that deprecates this
> behaviour [1], which could in the future be reverted to what is expected (at
> least what I expect) from the documents (except for an obscure note in [2]).
> 


Obviously, I am not against this ;). I have to admit it worries me a
bit, because there is quite a bit of code doing things like:

>>> slice_object = [slice(None)] * 5
>>> slice_object[2] = 3
>>> arr[slice_object]

and all of this code (numpy also has a lot of it), will probably have to
change the last line to be:

>>> arr[tuple(slice_object)]

So the implication of this might actually be more farther reaching then
one might think at first; or at least require quite a lot of code to be
touched (inside numpy that is no problem, but outside).

- Sebastian



> The discussion leading to this mail can be found here [3].
> 
> [1] https://github.com/numpy/numpy/pull/4434
> [2] http://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#advanced-indexing
> [3] https://github.com/numpy/numpy/issues/6564
> 
> 
> Thanks,
>   Lluis
> 

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 819 bytes
Desc: This is a digitally signed message part
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20151130/ece7c6e2/attachment.sig>


More information about the NumPy-Discussion mailing list