276

How can I check whether a numpy array is empty or not?

I used the following code, but this fails if the array contains a zero.

if not self.Definition.all():

Is this the solution?

if self.Definition == array([]):
Mokus
  • 10,174
  • 18
  • 80
  • 122
Kicsi Mano
  • 3,551
  • 3
  • 21
  • 26
  • 6
    `len(array( [] ))` is 0. `len(array( [0] )` is 1. – Steven Rumbalski Jul 02 '12 at 14:35
  • 3
    do you want to test for a zero-length array, an array containing all zeros, or both? What is your definition of 'empty'? – John Lyon Jul 03 '12 at 06:15
  • 15
    @StevenRumbalski: But `len(array([[]])` is 1 too! – strpeter Dec 19 '14 at 09:12
  • `len()` gives the number of dimensions in the first axis. But an array can have a non-zero dimension in the first axis but still be empty if it has a zero dimension in another axis. `size` is better as it is the product of all axes. – asmeurer Jun 26 '20 at 21:57

4 Answers4

455

You can always take a look at the .size attribute. It is defined as an integer, and is zero (0) when there are no elements in the array:

import numpy as np
a = np.array([])

if a.size == 0:
    # Do something when `a` is empty
André C. Andersen
  • 8,955
  • 3
  • 53
  • 79
JoshAdel
  • 66,734
  • 27
  • 141
  • 140
  • 6
    This is great for numpy, but is unfortunate that it is considered unpythonic for lists. Check out discussion for lists: https://stackoverflow.com/questions/53513/how-do-i-check-if-a-list-is-empty It would be nice to use same pattern for numpy arrays and lists. – eric Jul 28 '19 at 16:41
  • 1
    NumPy code in general doesn't work properly on lists, or visa-versa. You have to write code in a different way if you are using lists vs. NumPy arrays. – asmeurer Jun 26 '20 at 21:57
  • 10
    a quick equivalent `if not a.size:` – Tian Dec 02 '20 at 07:03
29

https://numpy.org/devdocs/user/quickstart.html (2020.04.08)

NumPy’s main object is the homogeneous multidimensional array. It is a table of elements (usually numbers), all of the same type, indexed by a tuple of non-negative integers. In NumPy dimensions are called axes. (...) NumPy’s array class is called ndarray. (...) The more important attributes of an ndarray object are:

ndarray.ndim
the number of axes (dimensions) of the array.

ndarray.shape
the dimensions of the array. This is a tuple of integers indicating the size of the array in each dimension. For a matrix with n rows and m columns, shape will be (n,m). The length of the shape tuple is therefore the number of axes, ndim.

ndarray.size the total number of elements of the array. This is equal to the product of the elements of shape.

Thrastylon
  • 853
  • 7
  • 20
Colonel Panic
  • 132,665
  • 89
  • 401
  • 465
26

One caveat, though. Note that np.array(None).size returns 1! This is because a.size is equivalent to np.prod(a.shape), np.array(None).shape is (), and an empty product is 1.

>>> import numpy as np
>>> np.array(None).size
1
>>> np.array(None).shape
()
>>> np.prod(())
1.0

Therefore, I use the following to test if a numpy array has elements:

>>> def elements(array):
    ...     return array.ndim and array.size

>>> elements(np.array(None))
0
>>> elements(np.array([]))
0
>>> elements(np.zeros((2,3,4)))
24
user10178557
  • 381
  • 4
  • 5
  • 16
    An array containing the `None` object is not an empty array, [see the answers here for further details](https://stackoverflow.com/questions/19473185/what-is-a-none-value) – DrBwts Jun 22 '19 at 12:28
  • 3
    @DrBwts that's not relevant to this answer. – vidstige Jul 02 '19 at 09:30
  • @DrBwts His array does not contain the `None` object. Look at its shape. – Navin Mar 02 '20 at 04:59
  • 4
    Arrays with shape `()` are scalar arrays, which do contain an element (the scalar). In this example, the scalar is `None` (`None` doesn't have any special meaning, this is just an object array). It depends on what you are doing but you most likely do want to consider scalar arrays as not being empty. – asmeurer Jun 26 '20 at 21:54
0

Why would we want to check if an array is empty? Arrays don't grow or shrink in the same that lists do. Starting with a 'empty' array, and growing with np.append is a frequent novice error.

Using a list in if alist: hinges on its boolean value:

In [102]: bool([])                                                                       
Out[102]: False
In [103]: bool([1])                                                                      
Out[103]: True

But trying to do the same with an array produces (in version 1.18):

In [104]: bool(np.array([]))                                                             
/usr/local/bin/ipython3:1: 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.
  #!/usr/bin/python3
Out[104]: False

In [105]: bool(np.array([1]))                                                            
Out[105]: True

and bool(np.array([1,2]) produces the infamous ambiguity error.

edit

The accepted answer suggests size:

In [11]: x = np.array([])
In [12]: x.size
Out[12]: 0

But I (and most others) check the shape more than the size:

In [13]: x.shape
Out[13]: (0,)

Another thing in its favor is that it 'maps' on to an empty list:

In [14]: x.tolist()
Out[14]: []

But there are other other arrays with 0 size, that aren't 'empty' in that last sense:

In [15]: x = np.array([[]])
In [16]: x.size
Out[16]: 0
In [17]: x.shape
Out[17]: (1, 0)
In [18]: x.tolist()
Out[18]: [[]]
In [19]: bool(x.tolist())
Out[19]: True

np.array([[],[]]) is also size 0, but shape (2,0) and len 2.

While the concept of an empty list is well defined, an empty array is not well defined. One empty list is equal to another. The same can't be said for a size 0 array.

The answer really depends on

  • what do you mean by 'empty'?
  • what are you really test for?
hpaulj
  • 221,503
  • 14
  • 230
  • 353