When I create an empty numpy array using foo = np.empty(1) the resulting array contains a float64:
>>> foo = np.empty(1)
>>> foo
array([ 0.])
>>> type(foo[0])
<type 'numpy.float64'>
Why doesn't it just return array([])?
3 Answers 3
You didn't read the documentation, which says:
Return a new array of given shape and type, without initializing entries.
empty has nothing to do with creating an array that is "empty" in the sense of having no elements. It just means the array doesn't have its values initialized (i.e., they are unpredictable and depend on whatever happens to be in the memory allocated for the array).
2 Comments
list.append requires creating a whole new array. Because of this, numpy arrays are not well suited for tasks that require arrays of dynamically changing size.foo = np.empty(0)
is what you need instead
you specified its size as 1, you need to set it as 0 instead like they told you in the comments
Comments
If you want an size=0 array of dimension N, you can use np.empty((0,)*N):
>>> np.empty((0,)*1)
array([], dtype=float64)
>>> np.empty((0,)*2)
array([], shape=(0, 0), dtype=float64)
Of course, if the array has .size == 0, then empty is the same as zeros
np.empty()is not the same as a list[]. It requires a parameter which you gave it. It sounds like you want a 0 size array. But why? That's rarely useful. See stackoverflow.com/questions/44872454/…np.empty()is shape. Shouldn't the code I used just generate an empty array of dimensions 1? By my understanding, if I saidnp.empty(2)I'd expect to getarray([[]]. How would I get that?[1],[1, 2], and[1, 2, 3]are all one-dimensional, but they have different shapes.emptyis probably not the best name for this function, given that anempty listhas a very different meaning.np.zerosornp.onesmight be a better starting point.