[Numpy-discussion] equivalent to isempty command in matlab (newbie question)
Filip Wasilewski
filip.wasilewski at gmail.com
Wed Dec 6 13:04:35 CST 2006
On 12/6/06, Robert Kern <robert.kern at gmail.com> wrote:
> Filip Wasilewski wrote:
>
> > Just like for other Python objects:
> >
> > if ifs3:
> > print "not empty"
>
> No, that doesn't work. numpy arrays do not have a truth value. They raise an
> error when you try to use them in such a context.
Right!
I could swear I have checked this before posting. Evidently I got
bitten by this:
>>> bool(numpy.array([]))
False
>>> bool(numpy.array([1]))
True
>>> bool(numpy.array([0]))
False
>>> bool(numpy.array([1,1]))
Traceback (most recent call last):
File "<pyshell#8>", line 1, in -toplevel-
bool(numpy.array([1,1]))
ValueError: The truth value of an array with more than one element is
ambiguous. Use a.any() or a.all()
So depending on the situation one can use len or size:
>>> len(numpy.array([[],[]]))
2
>>> numpy.array([[],[]]).size
0
And how to understand following?
>>> print numpy.array([1,1]) == [], numpy.array([1,1]) != []
False True
>>> print `numpy.array([1]) == []`, `numpy.array([1]) != []`
array([], dtype=bool) array([], dtype=bool)
>>> print bool(numpy.array([1]) == []), bool(numpy.array([1]) != [])
False False
cheers,
fw
More information about the Numpy-discussion
mailing list