How to dynamically access Numeric subarrays

Tim Hochberg tim.hochberg at
Wed Aug 4 16:13:24 CEST 2004

Gaubitzer Erwin wrote:
> Hi again
> For example I have an array AR whose shape is 
> (2, 1, 2, 1, 100, 3).
> and I want to access
> AR[0,0,0,0,:,1]
> which results in an rank 1 array with my wanted
> numbers (more advanced I want to loop through another
> index).
> I can write it manually but I can't insert this
> list of indices automatically, because the slice
> notation gives me an error when given to a python list.

I believe you want something like:

 >>> index = (0,0,0,0,slice(None,None),1)
 >>> AR[index]

The args to slice will vary depending on exactly what you want to do. 
slice can take up to three arguments for start, stop, step.

Since you seem to be delving deeply into the mysteries of numeric 
slicing, it may eventually help you to know that '...' is spelled
Ellipsis if you want to use it in a tuple as above.

Actually, the little class below will probably help you more than 
anything that I can write:

     class IndexInspector:
        def __getitem__(self, key):
             return key

Used like:

     II = IndexInspector()
     print II[0,0,0,0,:,1]
     print II[...,0,0,:,1]


     (0, 0, 0, 0, slice(None, None, None), 1)
     (Ellipsis, 0, 0, slice(None, None, None), 1)



> I tried to use take() but in my 6-dimensional array
> I wasn't able to find the right parameter combination
> to access the vector above.
> Maybe one can give me the right notation.
> Thanks again
> Erwin

More information about the Python-list mailing list