[Tutor] np array.any() question

Dave Angel d at davea.name
Fri Sep 21 17:37:23 CEST 2012

```On 09/21/2012 11:25 AM, Steven D'Aprano wrote:
> On 22/09/12 01:07, Bala subramanian wrote:
>> Friends,
>> May i know why do get a Valuerror if i check any value in a is between
>> 3.0 to 5.0 ?

To summarize,
with a numpy array called a, the OP is getting an error doing:

(3 < a < 5).any()

> This tries to calculate:
>
> (3 < a) and (a < 5)
>
> py> 3 < a
> array([False, False, False,  True,  True,  True], dtype=bool)
> py> a < 5
> array([ True,  True,  True,  True,  True, False], dtype=bool)
>
> but combining them with the "and" operator is ambiguous:
>
> py> (3 < a) and (a < 5)
> Traceback (most recent call last):
>   File "<stdin>", line 1, in <module>
> ValueError: The truth value of an array with more than one element
> is ambiguous. Use a.any() or a.all()
>
> Since the boolean "and" of the two arrays never gets calculated,
> the any method never gets called. You could do:
>
>
> py> (3 < a).any() and (a < 5).any()
> True
>
> which I think does what you want.
>

I think not.  The last expression you give will even return true if one
of the values is > 3 and a DIFFERENT value is < 5.   And i suspect the
OP only wants a TRUE if at least one item in the array is between 3 and 5.

I know nothing about numpy, but does it have a way to do an element-wise
AND of two bool arrays of the same size?  Maybe it's a function call and
not 'and'  Or maybe it's the & operator or something.

I find the operator overloading i've seen in numpy to be very confusing,