[Numpy-discussion] Logical AND on arrays

Alexander Schmolck a.schmolck at gmx.net
Mon Sep 9 15:25:03 CDT 2002

Tom Transue <transue at niehs.nih.gov> writes:

> If ar1 and ar2 are arrays, are the following two expressions supposed to give
> the same result?
>   (ar1 and ar2)
>   logical_and(ar1,ar2)
> The first form seems to return the value of the second array, which isn't very
Only if the boolean value of the first array is true (i.e. iff not all its
values are nonzero).

> useful.  It would be nice to map the first expression to do what the first does.

Impossible. Python's `and` and `or` are shortcircuting operators with a fixed
meaning. ``A and B`` only evaluates both ``A`` and ``B`` iff both have the
boolean value 'True' (e.g. ``0 and 0/1`` is OK because the second part never
gets evaluated), otherwise the first 'False` value is returned.

While each class is free to define a truth testing method (`__nonzero__`, or
`__len__` if `__nonzero__` doesn't exist; the convention is that empty
containers and zero numbers are false and pretty much everything else is
true), there is (luckily) no way to change the meaning of `and` and `or` (just
as one (luckily) can't change what the `if` statement does).

If this is still a bit unclear, I think this question has been raised before
in this list, so you should be able to find a thread in the archive.



Alexander Schmolck     Postgraduate Research Student
                       Department of Computer Science
                       University of Exeter
A.Schmolck at gmx.net     http://www.dcs.ex.ac.uk/people/aschmolc/

More information about the Numpy-discussion mailing list