0

I'm a little bit new to Python & Numpy, but I've noticed that when you call operator [] on a numpy array A, if it's a single index that is used (e.g., A[1]), the resulting sub-array is 1 dimension smaller, but if it's a range of indices (e.g., A[1:]) the dimension of the subarray remains unchanged, even if the range of indices covers only a single index, e.g., in this above case, if A was 2x2, A[1:] is effectively just a single index, but the resulting size is not the same as A[1].

My question is: is this always true in that if you supply a range of indices when extracting a subarray, the dimension doesn't change, and that a single index always reduces the dimension by 1? Are there edge cases?

student010101
  • 191
  • 2
  • 8

1 Answers1

1

That is always the case. When you use one index-value, e.g. A[1], you are effectively saying "give me the subarray A[1]", which, by definition, has a dimensionality smaller (by 1).

When you request a range of indices, e.g., A[1:] you are "cropping" A, to get everything but the first slice (A[0]). See, the range of indices define the axis you "lost" in the previous case (A[1]).

The following docs should be helpful to understand numpy arrays (indexing):

Brandt
  • 5,058
  • 3
  • 28
  • 46
  • Do you know where I can find documentation on how the slicing operators work internally? I also have some other questions beyond my OP, such as using multiple sets of brackets instead of commas, e.g., `A[1][2][3]` vs `A[1,2,3]`. I think I have a general idea of how it all works, but just wanted to consult some formal documentation rather than experimenting all the time – student010101 Jan 10 '22 at 16:18
  • 1
    multiple sets are applied sequentially. Have you looked up indexing in the official numpy docs? – hpaulj Jan 10 '22 at 16:33
  • @student010101 I updated my answer to what I think you should read to have a good understanding not only on indexing but the arrays themselves. – Brandt Jan 11 '22 at 10:27