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

2
  • 7
    np.array(0) is an array containing 0. whereas np.array([]) is an empty array containing nothing. Commented Nov 28, 2014 at 9:00
  • 3
    The real lesson to learn here is to check your results in between evaluations, it would have became obvious. Commented Nov 28, 2014 at 10:28

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Are you sure the 1st case create a 1-item array ? x.shape is ().
@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
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...
@dplamp This is expected behavior. array(0) a 'zero-dimensional' array, while array([0]) is a one-dimensional array.
@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 or this answer to get a bit more insight.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.