5

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([]) ?

Srivatsan
  • 9,225
  • 13
  • 58
  • 83
dpeng
  • 395
  • 2
  • 4
  • 17

1 Answers1

7

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.

Srivatsan
  • 9,225
  • 13
  • 58
  • 83
  • Are you sure the 1st case create a 1-item array ? x.shape is (). – dpeng Nov 28 '14 at 09:15
  • 1
    @dplamp yes, you are true.. But as mentioned in my answer, when you create `x = np.array(0)` you are creating `x` with the value `0`. So whatever you are going to append further to `x` will contain `0` along with the appended value – Srivatsan Nov 28 '14 at 09:24
  • That is not quite true, I think. My mistake is that array() takes an array-like object as its 1st argument, which is not the case in my '1st case'. Yet, it silently accepts it, which leads to a strange behaviour down the line. Hard to admit for a C++ guy... – dpeng Nov 28 '14 at 15:12
  • 1
    @dplamp This is expected behavior. `array(0)` a 'zero-dimensional' array, while `array([0])` is a one-dimensional array. – sebix Nov 29 '14 at 13:23
  • @dplamp `x = np.array(0)` creates a _scalar_, which is still an `array` (hence, `type(x)` would return `numpy.ndarray`), but is of empty shape. The whole handling of scalars vs. one-dimensional arrays seems a bit messy in numpy in general. Have a look at the [docs](http://docs.scipy.org/doc/numpy/reference/arrays.scalars.html) or [this](http://stackoverflow.com/questions/773030/why-are-0d-arrays-in-numpy-not-considered-scalar) answer to get a bit more insight. – tttthomasssss Aug 01 '15 at 10:41