Indexing with list of slices

Hi,
Is there any equivalent in torch to indexing with list of slices. The point is to be able to index without depending on the number of dimension. Example with numpy :

>>> x = torch.arange(0, 25).view(5, 5).numpy()
array([[  0.,   1.,   2.,   3.,   4.],
       [  5.,   6.,   7.,   8.,   9.],
       [ 10.,  11.,  12.,  13.,  14.],
       [ 15.,  16.,  17.,  18.,  19.],
       [ 20.,  21.,  22.,  23.,  24.]], dtype=float32)

>>> slicers=[slice(0,2), slice(0,2)]
>>> a[slicers]
array([[ 0.,  1.],
       [ 5.,  6.]], dtype=float32)

Thanks

I am not looking for a solution with slices specifically, just something that can index over dimensions, without dimension dependant writing.

Hi, just put your slices in a tuple and it will work:

>>> x = torch.arange(0, 25).view(5, 5)
  0   1   2   3   4
  5   6   7   8   9
 10  11  12  13  14
 15  16  17  18  19
 20  21  22  23  24
[torch.FloatTensor of size 5x5]

>>> slicers=(slice(0,2), slice(0,2))
>>> x[slicers]
 0  1
 5  6
[torch.FloatTensor of size 2x2]

1 Like

So simple, thanks @albanD :slight_smile: