# [Numpy-discussion] Why is the shape of a singleton array the empty tuple?

David Goldsmith d.l.goldsmith at gmail.com
Sun Mar 7 02:04:19 EST 2010

```On Sat, Mar 6, 2010 at 10:26 PM, Ian Mallett <geometrian at gmail.com> wrote:

> On Sat, Mar 6, 2010 at 9:46 PM, David Goldsmith <d.l.goldsmith at gmail.com>wrote:
>
>> Thanks, Ian.  I already figured out how to make it not so, but I still
>> want to understand the design reasoning behind it being so in the first
>> place (thus the use of the question "why (is it so)," not "how (to make it
>> different)").
>>
> exists?   Equating an array with a single number doesn't make sense to me.
> Ian
>

Here's an (unintended) use case:

I wanted to convert anything in an array that's close to zero to be zero
(and leave the rest as is), but I want it to be robust so that if it
receives a scalar, it can work w/ that, too.

Here's my (working) code (I'm sure that once Robert sees it, he'll be able
to replace it w/ a one-liner):

def convert_close(arg):
arg = N.array(arg)
if not arg.shape:
arg = N.array((arg,))
if arg.size:
t = N.array([0 if N.allclose(temp, 0) else temp for temp in arg])
if len(t.shape) - 1:
return N.squeeze(t)
else:
return t
else:
return N.array()

At first I wasn't "casting" arg to be an array upon entry, but I found that
if arg is a scalar, my list comprehension failed, so I had choose _some_
sort of sequence to cast scalars to; since arg will typically be an array
and that's what I wanted to return as well, it seemed most appropriate to
"cast" incoming scalars to arrays.  So I added the arg = N.array(arg) at the
beginning (N.array(array) = array, and N.array(non-array seq) does the
"right" thing as well), but the list comprehension still wouldn't work if
arg was a scalar upon entry; after many print statements and much
interactive experimenting, I finally figured out that this is because the
shape of N.array(scalar) is () (and I thence immediately guessed, correctly
of course, that N.array((scalar,)) has shape (1,)).  So I added the if not
arg.shape: to detect and correct for those zero size arrays, and now it
works fine, but I'd still like to know _why_ N.array(scalar).shape == () but
N.array((scalar,)).shape == (1,).  No biggy, just curious.

DG
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20100306/dfaf86bb/attachment.html>
```