# [Numpy-discussion] truthiness of object arrays

Antony Lee antony.lee at berkeley.edu
Thu Nov 13 01:19:35 EST 2014

```I know you can't in general, but this was in a context where I knew the
array contained a single element, which "works" (it checks the truthiness
of the contained element).  Of course I didn't consider the case where the
element contained was itself a (non-trivial) array, thus the finding.
The link you posted doesn't seem to address what magic numpy can do to make
"bool(x)" and "if x:" have different behaviors (FWIW, "t.__bool__()" also
returns True).
Antony

2014-11-12 20:15 GMT-08:00 Michael Sarahan <msarahan at gmail.com>:

> 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
>>
>>
>
> _______________________________________________
> 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/ea147e19/attachment.html>
```