# [Numpy-discussion] Why is the truth value of ndarray not simply size>0 ?

josef.pktd@gmai... josef.pktd@gmai...
Sun Sep 13 09:55:11 CDT 2009

```On Sun, Sep 13, 2009 at 9:05 AM, Alan G Isaac <aisaac@american.edu> wrote:
> On 9/13/2009 7:46 AM, Robert wrote:
>> 2 ways seem to be consistently Pythonic and logical: "size>
>> 0"; or "any(a)" (*); and the later option may be more 'numerical'.
>
> Well, *there's* the problem.
>
> As a user I have felt more than once that a
> length based test, like other containers, would
> be natural, so I that I could do the usual test
>        if a:
> That would certainly prove problematic for
> the `any` test when a is an array of zeros.
> And  then soon after I want to use
>        if (a>0):
> and that would certainly prove problematic for
> the `len` test when (a>0) is an array of zeros.
> And as for the `any` test, well in this case I
> usually want `all`.
>
> So the ValueError has proved useful.
>
> Alan Isaac
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion@scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>

In a numerical context, I essentially stopped using
if a: ...

I don't think a single definition is common enough to avoid
an ambiguous interpretation, and the ValueError is a good
reminder to be more precise.
I don't see why zero should evaluate as False, except for booleans,
even for scalars and also in python. zeros are useful numbers
and throwing them together with None is pretty confusing.

But I agree with the initial post that for single numbers
the numpy behavior is not completely consistent.

>>> a=np.array(0)
>>> if not a: print 'not true'

not true
>>> a=np.array([0])
>>> if not a: print 'not true'

not true
>>> a=np.array([])
>>> if not a: print 'not true'

not true
>>> np.array([0]).shape
(1,)
>>> np.array(0).shape
()
>>> np.array([]).shape
(0,)

I don't think np.array([0]) should evaluate to false.

But  "if a.size==0:" or "if a==0:" or if np.any(a==0):"
is much clearer.

Josef
```