[Numpy-discussion] Accessing rank-0 array value?

Perry Greenfield perry at stsci.edu
Mon Jun 7 10:36:01 CDT 2004


Peter Verveer wrote:
> 
> I do not agree. The a[()] notation is consistent and clear if you know 
> that you can index with a tuple of indices: you index a rank-0 array 
> with a tuple of length zero.
> 
> The "..." and ":" should do the same as for any other array: return the 
> whole thing, not a single element.
> 
Peter gets at the crux of the reasons behind the current behavior.
(Much of this was discussed some time ago). There is a distinction
between a scalar and a rank-0 array in that one expects that
all the array semantics will be consistent with all other arrays.
Thus "..." and ":" behave exactly the same.

That discussion was centered on whether single element indexing
should return rank-0 arrays or scalars. We chose scalars 
as more intuitive (and for performance reasons as well).
There was hope that rank-0 arrays would be more convenient
to use, and that they could also be indexed as a[0], however
this is inconsistent with the shape as Peter points out (and
as others before did as well).

That being said, I'd like to understand why you (Francesc)
would like to use rank-0 arrays. There is certainly a legitimate
problem to be solved, and perhaps there are better alternatives.

The original source of the previous rank-0 discussion was that
they aided what had been dubbed "generic programming". This 
was being promoted primarily by the scipy guys and the general
idea was to make it easier to write code that did not constantly
have to check whether an input was scalar or an array. With
scalars always mapping to rank-0 arrays, it was felt that
this would aid writing code that would work for both scalars
and arrays without any conditional tests. It's a good thing
to want. I wonder if we should now develop tools to make writing
such code much easier.

Matlab apparently treats all scalars as rank-0 values and thus
makes it fairly easy to deal with such things. On the other hand,
Python does have real scalars so things are not quite so simple.
One can wrap all inputs with array(), but then what will be returned
will also be an array (rank-0 or whatever). That isn't always what
is desired when scalars are given as an argument to a function.

So if your needs are along this line, this seems like a good time
to try to figure out ways of dealing with such issues.

Perry




More information about the Numpy-discussion mailing list