Advanced indexing doesn't follow the Principle of least astonishment
![](https://secure.gravatar.com/avatar/e339113882d61e424c5f0ae24645cd96.jpg?s=120&d=mm&r=g)
Hi all, New to the mailing list, so I hope I'm creating a discussion in the right place. Am I the only one that thinks that Advanced indexing in numpy doesn't follow the principle of minimum astonishment? for example ```python a = np.random.rand(100, 100) a[(2,4)] #this yields the element at [2,4] a[[2,4]] #this yields the rows at position 2 and 4 a[1, (2,4)] #this yields the 2nd and 4th elements of row 1. (So actually does advanced indexing) a[1, [2,4]] # Works the same way as the previous one. ``` Worst of all, it's very easy for someone do a mistake and not notice it: it seems to me that the first method, a[(2,4)], should not be allowed, and instead only a[*(2,4)] should work. How checked how it works in Julia (which has a similar syntax), and a[(2,4)] would yield an error, which makes sense to me. Could it be an idea to deprecate a[(2,4)]-like usages?
![](https://secure.gravatar.com/avatar/764323a14e554c97ab74177e0bce51d4.jpg?s=120&d=mm&r=g)
On Thu, Dec 29, 2022 at 8:50 AM Diogo Valada <diogovalada.7@hotmail.com> wrote:
No, that's not possible. In Python syntax, the comma `,` is what creates the tuple, not the parentheses. So `a[(2,4)]` is exactly `a[2, 4]`. `a[2, 4]` translates to `a.__getitem__((2, 4))`. So there's no way for the array to know whether it got `a[2, 4]` or `a[(2, 4)]`. -- Robert Kern
![](https://secure.gravatar.com/avatar/03f2d50ce2e8d713af6058d2aeafab74.jpg?s=120&d=mm&r=g)
On Thu, Dec 29, 2022, at 16:34, Robert Kern wrote:
To add to what Robert wrote, the other problem is that `a[*(2, 4)]` _does not_ work, it's a syntax error. And if you look at dicts for instance, `d[2, 4] = 42` will give you a tuple-valued key (this is just a standard-library example of what Robert said about `__getitem__()`). So there's really no choice for NumPy here, this is Python syntax. András
![](https://secure.gravatar.com/avatar/764323a14e554c97ab74177e0bce51d4.jpg?s=120&d=mm&r=g)
On Thu, Dec 29, 2022 at 8:50 AM Diogo Valada <diogovalada.7@hotmail.com> wrote:
No, that's not possible. In Python syntax, the comma `,` is what creates the tuple, not the parentheses. So `a[(2,4)]` is exactly `a[2, 4]`. `a[2, 4]` translates to `a.__getitem__((2, 4))`. So there's no way for the array to know whether it got `a[2, 4]` or `a[(2, 4)]`. -- Robert Kern
![](https://secure.gravatar.com/avatar/03f2d50ce2e8d713af6058d2aeafab74.jpg?s=120&d=mm&r=g)
On Thu, Dec 29, 2022, at 16:34, Robert Kern wrote:
To add to what Robert wrote, the other problem is that `a[*(2, 4)]` _does not_ work, it's a syntax error. And if you look at dicts for instance, `d[2, 4] = 42` will give you a tuple-valued key (this is just a standard-library example of what Robert said about `__getitem__()`). So there's really no choice for NumPy here, this is Python syntax. András
participants (3)
-
Andras Deak
-
Diogo Valada
-
Robert Kern