Sometimes I have a situation where I want to test whether a variable is 0
or None
or not. In pure Python, this is simply
foo == True
but when foo
is possibly a Numpy object (such as numpy.ndarray
), this does not work anymore and I get the error:
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
and in this case I want a.any()
, however this fails on non-iterable objects.
Of course I can explicitly check if foo
is 0
or None
, but I am wondering if there is a more elegant way to do this.
How can I check if an arbitrary object (both iterable and not) is True
or not?
Advertisement
Answer
Just use np.all
or np.any
instead of the .all
method. np.all
will create an array if it is not one yet.