[Numpy-discussion] preferred way of testing empty arrays

Benjamin Root ben.root@ou....
Fri Jan 27 14:57:52 CST 2012


On Fri, Jan 27, 2012 at 2:46 PM, Bartosz Telenczuk <
b.telenczuk@biologie.hu-berlin.de> wrote:

> I have been using numpy for several years and I am very impressed with its
> flexibility. However, there is one problem that has always bothered me.
>
> Quite often I need to test consistently whether a variable is any of the
> following: an empty list, an empty array or None. Since both arrays and
> lists are ordered sequences I usually allow for both, and convert if
> necessary. However, when the (optional) argument is an empty list/array or
> None,  I skip its processing and do nothing.
>
> Now, how should I test for 'emptiness'?
>
> PEP8 recommends:
>
> For sequences, (strings, lists, tuples), use the fact that empty sequences
> are false.
>
> >> seq = []
> >> if not seq:
> ...    print 'Hello'
>
> It works for empty numpy arrays:
>
> >> a = np.array(seq)
> >> if not a:
> ...     print 'Hello"
> Hello
>
> but if 'a' is non-empty it raises an exception:
>
> >> a = np.array([1,2])
> >> if not a:
> ...     print 'Hello"
> ValueError: The truth value of an array with more than one element is
> ambiguous. Use a.any() or a.all()
>
> One solution is to test lengths:
>
> >> if len(seq) > 0:
> ....    ...
> >> if len(a) > 0:
> ...     ...
>
> but for None it fails again:
>
> >> opt = None
> >> if len(opt):
> ...
> TypeError: object of type 'NoneType' has no len()
>
> even worse we can not test for None, because it will fail if someone
> accidentally wraps None in an array:
>
> >> a = np.array(opt)
> >> if opt is not None:
> ...      print 'hello'
> hello
>
> Although this behaviour is expected, it may be very confusing and it
> easily leads to errors. Even worse it adds unnecessary complexity in the
> code, because arrays, lists and None have to be handled differently.
>
> I hoped the I managed to explain the problem well. Is there a recommended
> way to test for empty arrays?
>
> Cheers,
>
> Bartosz
>
>
Don't know if it is recommended, but this is used frequently within
matplotlib:

if np.prod(a.shape) == 0 :
   print "Is Empty!"

Cheers!
Ben Root
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.scipy.org/pipermail/numpy-discussion/attachments/20120127/c15099ef/attachment.html 


More information about the NumPy-Discussion mailing list