0

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?

2
  • 1
    Is the code for a list and an array identical? Commented Apr 10, 2017 at 17:58
  • Yes, the same code is executed if the element is not empty. Commented Apr 10, 2017 at 17:59

1 Answer 1

5

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
Sign up to request clarification or add additional context in comments.

3 Comments

I like the second solution :)
I suspect the OP isn't concerned with 'scalar' arrays. I rarely deal with those; and if I did, I wouldn't be asking if it was empty. So the len(a) answer might quite useful.
I don't doubt that but np.asarray (or np.asanyarray when subclasses should pass through) is in my view the "most pythonic approach". At least if numpy functions are used on a they will cast it to an array anyway.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.