Why can I do "[:]" in a numpy array as many times as I want?

Viewed 65

I thought that I understood how numpy array works, until, by mistake a I did something like

x = np.array([2,3,1,0])
x[:][:] 

and I got the same result as x[:] and the same as x[:][:][:] And now I wonder how is this possible if x is 1-D array!

I don't know if it is too basic or I'm missing something. Thanks.

1 Answers

The expression x[:][:], is short for (x[:])[:]. If you write x[:], then you generate a "view" on the array x, this view takes all elements into account of x, and thus is a numpy array with exactly the same shape.

Although x[:] and x are different objects, these thus contain the same data, and in the same shape. By calling (x[:])[:], you thus create another view. Numpy will see that x[:] is a view on x, and thus make another view on x, but this is thus again a view. You thus can repeat the same "trick" an arbitrary number of times.

Related