[Numpy-discussion] Why is the truth value of ndarray not simply size>0 ?
Robert
kxroberto@googlemail....
Mon Sep 7 07:11:59 CDT 2009
Is there a reason why ndarray truth tests (except scalars)
deviates from the convention of other Python iterables
list,array.array,str,dict,... ?
Furthermore there is a surprising strange exception for arrays
with size 1 (!= scalars).
I often run into exceptions and unexpected bahavior like shown
below, when developing or transcribing from other types to numpy.
Robert
---
>>> a=np.array([12,4,5])
>>> if a: print 2
...
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
ValueError: The truth value of an array with more than one element
is ambiguous. Use a.any() or a.all()
>>> a=np.array([12])
>>> if a: print 2
...
2
>>> a=np.array([0])
>>> if a: print 2
...
>>> a=[0]
>>> if a: print 2
...
2
>>> a=[]
>>> if a: print 2
...
>>> import array
>>> a=array.array('i',[12,1,3])
>>> if a: print 2
...
2
>>> a=array.array('i',[0])
>>> if a: print 2
...
2
>>> a=array.array('i',[])
>>> if a: print 2
...
>>> bool(np.array(0))
False
More information about the NumPy-Discussion
mailing list