What's the difference between X[0] and X[0,:]

In the assignment of DLS 1 week 3:
X is a (2,400) array, it looks X[0] and X[0,:] are the same and the diagram made by the following two lines of code are the same too.
plt.scatter(X[0,:], X[1,:], c=Y, s=40, cmap=plt.cm.Spectral);
plt.scatter(X[0], X[1], c=Y, s=40, cmap=plt.cm.Spectral);
So why use X[0,:] instead of X[0]? Does X[0,:] make any differences?

Thank you.

1 Like

If you write X[0] for a Numpy ndarray it interprets this as X[0,:,:,…,:]. So, you get no difference in the result (AFAIK).

I would always write X[0,:] instead of X[0], because it is clearer.


Dear @cppiod,

Difference between X[0] and X[0, :] depends on the dimensionality of the array X.

1-Dimensional Array

If X is a 1-dimensional array, X[0] returns the element at the first index.
X[0, :] would result in an error because you are trying to use slicing ( : ) along the second axis, which doesn’t exist in a 1-dimensional array.

2-Dimensional Array
If X is a 2-dimensional array, both X[0] and X[0, :] will return the first row of the array.

1 Like

The other subtlety here would be to make sure that the “shape” of the output is the same. Here’s a little experiment that shows that it is. Notice that the output is a 1D array in both cases. You start with a 2D array and you “slice” it on one dimension.

A = np.random.randint(0, 10, (3,5))
print(f"A.shape {A.shape}")
print(f"A =\n{A}")
A0 = A[0]
print(f"A0.shape {A0.shape}")
print(f"A0 =\n{A0}")
A0plus = A[0,:]
print(f"A0plus.shape {A0plus.shape}")
print(f"A0plus =\n{A0plus}")
A.shape (3, 5)
A =
[[6 3 7 4 6]
 [9 2 6 7 4]
 [3 7 7 2 5]]
A0.shape (5,)
A0 =
[6 3 7 4 6]
A0plus.shape (5,)
A0plus =
[6 3 7 4 6]

Thank you for the clear display in both cases.

1 Like