Gabriel
Gabriel

Reputation: 42329

Check if list or array element is empty

I know how to check if a list is empty (Best way to check if a list is empty) and how to check if a numpy array is empty (How can I check whether the numpy array is empty or not?)

I have an element that can be at times a list, and other times an array. I need to check whether this element is empty, without knowing beforehand which one it is. I can think of doing

if isinstance(a, list):
    if a:
        # do something
elif a.any():
    # do something

But I wonder if there might be a more pythonic way of doing this?

Upvotes: 0

Views: 19118

Answers (1)

MSeifert
MSeifert

Reputation: 152647

You could use the size attribute.

a = np.asarray(a)  # converts it to an array if it's not an array.
if a.size == 0:
    # it's empty!

This works also for lists because of the np.asarray. You haven't specified what you want to do if it's not empty but given that you allow numpy.ndarrays it's likely the operations will convert it to an array anyway so you won't have much overhead with the np.asarray-call

If you really don't want the overhead of np.asarray:

if not getattr(a, 'size', len(a)):  # However this does not work on numpy scalars
    # it's empty

Upvotes: 5

Related Questions