[Numpy-discussion] preferred way of testing empty arrays

Robert Kern robert.kern@gmail....
Fri Jan 27 15:29:39 CST 2012


On Fri, Jan 27, 2012 at 21:24, Bartosz Telenczuk
<b.telenczuk@biologie.hu-berlin.de> wrote:
> Thank you for your tips. I was not aware of the possible problems with len.
>
>> There is no way to test all of the cases (empty sequence, empty array,
>> None) in the same way. Usually, it's a bad idea to conflate the three.
>
> I agree that this should be avoided. However, there are cases in which it is not possible or hard. My case is that I get some extra data to add to my plots from a database. The dataset may be undefined (which means None), empty array or empty list. In all cases the data should not be plotted. If I want to test for all the cases, my program becomes quite complex.

Well, if you really need to do this in more than one place, define a
utility function and call it a day.

def should_not_plot(x):
    if x is None:
        return True
    elif isinstance(x, np.ndarray):
        return x.size == 0
    else:
        return bool(x)

> In fact, Python provides False values for most empty objects, but NumPy seems to ignore this. It might be a good idea to have a helper function which handles all objects consistently.

np.asarray(x).size == 0

None should rarely be treated the same as an empty list or a 0-size
array, so that should be left to application-specific code.

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless
enigma that is made terrible by our own mad attempt to interpret it as
though it had an underlying truth."
  -- Umberto Eco


More information about the NumPy-Discussion mailing list