[Numpy-discussion] multi-comparison expressions
Mon Oct 6 14:59:34 CDT 2008
On Mon, Oct 6, 2008 at 14:32, John <firstname.lastname@example.org> wrote:
> 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.
"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
-- Umberto Eco
More information about the Numpy-discussion