Reputation: 8029
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...
Upvotes: 1
Views: 2211
Reputation: 35125
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: ndarray
s 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.
Upvotes: 1