# [Numpy-discussion] truthiness of object arrays

Michael Sarahan msarahan at gmail.com
Wed Nov 12 23:15:18 EST 2014

```Hi Antony,

In general, you can't use numpy arrays in if statements without using any()
or all() or some other means of obtaining a single boolean value from the
whole array.

I think your confusion is that bool() uses truth testing rules outlined
here: https://docs.python.org/release/2.5.2/lib/truth.html

If statements in theory have equivalent behavior, but take slightly
different paths (they don't call bool() directly).  This SO post was
enlightening to me:
http://stackoverflow.com/questions/11885382/is-there-any-difference-between-if-boolx-and-if-x-in-python

Without looking at Numpy's code, I'd bet Numpy arrays probably define
__bool__ or __nonzero__ in such a way that the ValueError is raised when it
makes sense to do so.

HTH,
Mike

On Tue, Nov 11, 2014 at 12:46 PM, Antony Lee <antony.lee at berkeley.edu>
wrote:

> I am puzzled by the following (numpy 1.9.0, python 3.4.2):
>
> In [1]: t = array(None); t[()] = array([None, None])  # Construct a 0d
> array of dtype object, containing a single numpy array with 2 elements
>
> In [2]: bool(t)
> Out[2]: True
>
> In [3]: if t: pass
> ---------------------------------------------------------------------------
> ValueError                                Traceback (most recent call last)
> ValueError: The truth value of an array with more than one element is
> ambiguous. Use a.any() or a.all()
>
> I thought that "if x" simply calls "bool", but apparently this is not even
> the case...
>
> Antony
>
> _______________________________________________
> NumPy-Discussion mailing list
> NumPy-Discussion at scipy.org
> http://mail.scipy.org/mailman/listinfo/numpy-discussion
>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20141112/7414aaf0/attachment.html>
```