0

Suppose a is an array_like and we want to check if it is empty. Two possible ways to accomplish this are:

if not a:
   pass

if numpy.array(a).size == 0:
   pass

The first solution would also evaluate to True if a=None. However I would like to only check for an empty array_like.

The second solution seems good enough for that. I was just wondering if there is a numpy built-in function for that or a better solution then to check for the size?

2
  • 2
    You definitely should not use the expression not a. If a is, in fact, a numpy array with size 0, in recent versions of numpy that expression will generate a deprecation warning: DeprecationWarning: The truth value of an empty array is ambiguous. Returning False, but in future this will result in an error. Use array.size > 0 to check that an array is not empty. And that messages suggests that checking the size attribute is the recommended method. Commented Jan 7, 2023 at 12:09
  • 1
    Also note that if a is a list such as a = [[], [], []], then not a will be False (because len(a) is 3), but np.array(a).size is 0 (because the array that is created has shape (3, 0)). Commented Jan 7, 2023 at 12:17

1 Answer 1

2

If you want to check if size is zero, you might use numpy.size function to get more concise code

import numpy
a = []
b = [1,2]
c = [[1,2],[3,4]]
print(numpy.size(a) == 0)  # True
print(numpy.size(b) == 0)  # False
print(numpy.size(c) == 0)  # False
Sign up to request clarification or add additional context in comments.

Comments

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.