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?
if foo- and that'll work with most things. Unfortunately, you'll have to special casenumpy.ndarrayor any other type that's more complex than 0, None, False, len() == 0 equates to False.array is None, but this doesn't check for zero though. See here for a similar question, stackoverflow.com/questions/5086178/…