is it possible for numpy to use a single subscript without a comma in a nmapty file

Define a simple class with a getitem, indexing method:

In [128]: class Foo():
     ...:     def __getitem__(self, arg):
     ...:         print(type(arg), arg)
     ...: 
In [129]: f = Foo()

And look at what different indexes produce:

In [130]: f[:]
<class 'slice'> slice(None, None, None)
In [131]: f[1:2:3]
<class 'slice'> slice(1, 2, 3)
In [132]: f[:, [1,2,3]]
<class 'tuple'> (slice(None, None, None), [1, 2, 3])
In [133]: f[:, :3]
<class 'tuple'> (slice(None, None, None), slice(None, 3, None))
In [134]: f[(slice(1,None),3)]
<class 'tuple'> (slice(1, None, None), 3)

For builtin classes like list, a tuple argument raises an error. But that’s a class dependent issue, not a syntax one. numpy.ndarray accepts a tuple, as long as it’s compatible with its shape.

The syntax for a tuple index was added to Python to meet the needs of numpy. I don’t think there are any builtin classes that use it.

The numpy.lib.index_tricks.py module has several classes that take advantage of this behavior. Look at its code for more ideas.

In [137]: np.s_[3:]
Out[137]: slice(3, None, None)
In [139]: np.r_['0,2,1',[1,2,3],[4,5,6]]
Out[139]: 
array([[1, 2, 3],
       [4, 5, 6]])
In [140]: np.c_[[1,2,3],[4,5,6]]
Out[140]: 
array([[1, 4],
       [2, 5],
       [3, 6]])

other “indexing” examples:

In [141]: f[...]
<class 'ellipsis'> Ellipsis
In [142]: f[[1,2,3]]
<class 'list'> [1, 2, 3]
In [143]: f[10]
<class 'int'> 10
In [144]: f[{1:12}]
<class 'dict'> {1: 12}

I don’t know of any class that makes use of a dict argument, but the syntax allows it.

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top