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?

0

1 Answer 1

4

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

3 Comments

Does len(a) returns the same as a.size ? It would then be convenient to use interchangeably for input lists or input arrays.
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.
a.size > 0 would save you a keystroke :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.