I wonder if there is a rationale behind the fact that np.size('') returns 1, given the fact that len('') or np.size([]), for instance, both return 0.
I wonder if there is a rationale behind the fact that np.size('') returns 1, given the fact that len('') or np.size([]), for instance, both return 0.
np.size of any str is 1. This is also true of most Python objects which are not lists.
Calling help on it prints:
Help on function size in module numpy:
size(a, axis=None)
Return the number of elements along a given axis.
Parameters
----------
a : array_like
Input data.
axis : int, optional
Axis along which the elements are counted. By default, give
the total number of elements.
Returns
-------
element_count : int
Number of elements along the specified axis.
...
From this we see that the provided first argument ought to be "array_like", and so should not be a str in any case.
The source code of the body of np.size is:
if axis is None:
try:
return a.size
except AttributeError:
return asarray(a).size
else:
try:
return a.shape[axis]
except AttributeError:
return asarray(a).shape[axis]
When provided a str, it calls asarray on the object. This results in a 0-dimensional array being created, which will always have a size of 1.
>>> a = np.asarray('')
>>> a
array('', dtype='<U1')
>>> a.size
1
>>> a.ndim
0
>>>
>>> b = np.asarray('example str')
>>> b
array('example str', dtype='<U11')
>>> b.size
1
>>> b.ndim
0