1

I wrote the following code:

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

this returned false. Why is this the case? How do I check an array is non-empty?

Lost1
  • 990
  • 1
  • 14
  • 34

1 Answers1

3

Well, [] is an empty Python list object, while np.array([0.1]) is a numpy array. You can't really compare the two as you have done; a better way would be to access the size property of the numpy array (also mentioned here).

a = np.array([0.1])
assert a.size != 0
David O'Neill
  • 330
  • 2
  • 13
  • Does `len(a)` returns the same as `a.size` ? It would then be convenient to use interchangeably for input lists or input arrays. – PlasmaBinturong Mar 13 '19 at 14:02
  • 1
    The only case in which `len(a)` will return the same result as `a.size` is in the case of single-dimensional arrays, where the length is the same as the number of elements in the array. For example, if `z = np.zeros(shape=(10))`, then `len(z)` and `z.size` return the same value. However, in the case of `...shape=(100,10,10)...`, `len(z)` would return the same value as `z.shape[0]`, or the first shape dimension. `z.size` would return `100 * 10 * 10`. – David O'Neill Mar 14 '19 at 18:08