Reputation: 487
1st case :
>>> import numpy as np
>>> x=np.array(0)
>>> x=np.append(x,1)
>>> x
array([0, 1])
x
contains 2 elements. Why is that ?!
2nd case :
>>> x=np.array([])
>>> x=np.append(x,1)
>>> x
array([ 1.])
x
contains 1 element, as expected.
What's the difference between np.array(0)
and np.array([])
?
Upvotes: 5
Views: 14337
Reputation: 9363
In your first case, you are creating an array called x
that will containing one value, which is 0
.
In your second case you are creating an empty array called x
that will contain no values, but is still an array.
FIRST CASE
So when you append x = np.append(x,1)
, the value 1
get's appended to your array (which already contains 0) i.e. it now contains 0 and 1
SECOND CASE
Since you have no values in the empty array, when you append x=np.append(x,1)
the value 1
get's appended and the length of x
becomes 1 (i.e. it now contains only 1)
P.S. I believe you might have thought that calling x = np.array(0)
with the 0
would make it an empty array, it doesn't!! In Python, 0 is still taken to be a number and is appended to the array.
Upvotes: 7