1

I am testing some edge cases of my program and observed a strange fact. When I create a scalar numpy array, it has size==1 and ndim==0.

>>> A=np.array(1.0)
>>> A.ndim  # returns 0
>>> A.size  # returns 1

But when I create empty array with no element, then it has size==0 but ndim==1.

>>> A=np.array([])
>>> A.ndim  # returns 1
>>> A.size  # returns 0

Why is that? I would expect the ndim to be also 0. Or is there another way of creation of 'really' empty array with size and ndim equal to 0?

UPDATE: even A=np.empty(shape=None) does not create dimensionless array of size 0...

  • 2
    Because it's a **1**-D array. – Ashwini Chaudhary Jan 29 '15 at 11:22
  • OK, I agree... if I used `A=np.array([[]])` I would get `ndim==2`... This seems logical. But is there a way to create a dimensionless array with size 0? – HiFile.app - best file manager Jan 29 '15 at 11:23
  • I rewrote the title of my question a bit. – HiFile.app - best file manager Jan 29 '15 at 11:45
  • 1
    What use do you have for such a contraption? – Jaime Jan 29 '15 at 14:50
  • I am asking for two reasons: 1) curiosity, which is a thing that will help you understand and learn 2) my function/class/whatever takes a numpy ndarray and does some pretty complicated operations on it. I found it fails when I put scalar in it so I rewrote it to become more robust. Then I found it fails when I put empty multidimensional array in it so I rewrote it again... I finally if it is possible to put a zero dimension array of size zero, I am likely to rewrite it again. But I do not know if such a thing - zero dimensional array with size of zero - even exists... – HiFile.app - best file manager Jan 30 '15 at 09:31

1 Answers1

1

I believe the answer is that "No, you can't create an ndarray with both ndim and size of zero". As you've already found out yourself, the (ndim,size) pairs of (1,0) and (0,1) are as low as you can go.

This very nice answer explains a lot about numpy scalar types, and why they're a bit odd to have around. This explanation makes it clear that scalar numpy arrays like array(1) are a very special kind of beast. They only have a single value (causing size==1), but by definition they don't have a sense of dimensionality, hence ndim==0. Non-scalar numpy arrays, on the other hand, can be empty, but they contain at least a pair of square brackets, leading to a minimal ndim of 1, even if their size can be 0 if they are made up of empty lists. (This is how I think about the situation: ndarrays are in a way lists of lists of lists of ..., on as many levels as there are dimensions. 1d arrays are compatible with lists, so an empty list, being still a list, also has a defining dimension.)

The only way to come up with an empty scalar would be to call np.array() like this, but arrays can only be initialized by some actual object. So I believe your program is safe from this edge case.

Community
  • 1
  • 1