[Numpy-discussion] preferred way of testing empty arrays

Bartosz Telenczuk b.telenczuk@biologie.hu-berlin...
Fri Jan 27 14:46:06 CST 2012


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



More information about the NumPy-Discussion mailing list