[Numpy-discussion] multi-comparison expressions

Charles R Harris charlesr.harris at gmail.com
Mon Oct 6 16:58:12 EDT 2008


On Mon, Oct 6, 2008 at 1:59 PM, Robert Kern <robert.kern at gmail.com> wrote:

> On Mon, Oct 6, 2008 at 14:32, John <john at saponara.net> wrote:
> > hi,
> >
> > why does the ValueError appear below, and how can i make that 2<a<5
> > expression work when a is an array?
>
> (2<a<5) evaluates to ((2<a) and (a<5)). The "and" keyword coerces its
> arguments to actual boolean True or False objects, so this is actually
> (bool(2<a) and bool(a<5)). Arrays implement rich comparisons, so if
> 'a' is an array, then (2<a) is an array of bools. bool(some_array) is
> ambiguous; sometimes you want it to be True if any of the elements are
> True and sometimes you only want it to be True if all of the elements
> are True. Consequently, numpy refuses to guess what you want and makes
> you specify with the .any() and .all() methods. Unfortunately, this
> means that (2<a<5) will never work for arrays.
>

This reminds me that if we add matrix operators to python it would also be
nice to have some for the logical operators.  Having && and || would be
handy.

Chuck
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/numpy-discussion/attachments/20081006/46264fb0/attachment.html>


More information about the NumPy-Discussion mailing list