Rich Comparisons Gotcha

James Stroud jstroud at mbi.ucla.edu
Sun Dec 7 19:39:09 EST 2008


Steven D'Aprano wrote:
> On Sun, 07 Dec 2008 13:57:54 -0800, James Stroud wrote:
> 
>> Rasmus Fogh wrote:

>>>>>> ll1 = [y,1]
>>>>>> y in ll1
>>> True
>>>>>> ll2 = [1,y]
>>>>>> y in ll2
>>> 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()
>> I think you could be safe calling this a bug with numpy. 
> 
> Only in the sense that there are special cases where the array elements 
> are all true, or all false, and numpy *could* safely return a bool. But 
> special cases are not special enough to break the rules. Better for the 
> numpy caller to write this:
> 
> a.all() # or any()
> 
> instead of:
> 
> try:
>     bool(a)
> except ValueError:
>     a.all()
> 
> as they would need to do if numpy sometimes returned a bool and sometimes 
> raised an exception.

I'm missing how a.all() solves the problem Rasmus describes, namely that 
the order of a python *list* affects the results of containment tests by 
numpy.array. E.g. "y in ll1" and "y in ll2" evaluate to different 
results in his example. It still seems like a bug in numpy to me, even 
if too much other stuff is broken if you fix it (in which case it 
apparently becomes an "issue").

James



More information about the Python-list mailing list