[Numpy-discussion] Truth value of an array

Anne Archibald peridot.faceted@gmail....
Fri Apr 18 16:09:50 CDT 2008

On 18/04/2008, Robert Kern <robert.kern@gmail.com> wrote:
> On Fri, Apr 18, 2008 at 3:33 PM, Joe Harrington <jh@physics.ucf.edu> wrote:
>  > For that matter, is there a reason logical operations don't work on
>  >  arrays other than booleans?  What about:
> The keywords "and", "or", and "not" only work on bool objects; Python
>  tries to convert the operands using bool(). bool(some_array) raises
>  the exception just as we've been discussing.

This is a bit misleading, as the actual value is returned:

In [167]: "" or "A"
Out[167]: 'A'

In [168]: "A" and "B"
Out[168]: 'B'

In fact the problem is that "and" and "or" are short-circuiting, which
means that "return X or Y" is equivalent to something like:
if X:
    return X
elif Y:
    return Y
    return False

These are handled specially by syntax so that, for example, you can do
"False and 1/0" and not raise a ZeroDivisionError. So "and" and "or"
aren't even really operators, and it's not just impossible to change
them but unlikely to ever become possible. Just cast your arrays to
booleans if you want to do boolean operations on them.


More information about the Numpy-discussion mailing list