Single element indexing
Single element indexing works exactly like that for other standard Python sequences. It is 0-based, and accepts negative indices for indexing from the end of the array.
x = np.arange(10)
x[2]
2
x[-2]
8
It is not necessary to separate each dimension’s index into its own set of square brackets.
x.shape = (2, 5) # now x is 2-dimensional
x[1, 3]
8
x[1, -1]
9
Note that if one indexes a multidimensional array with fewer indices than dimensions, one gets a subdimensional array. For example:
x[0]
array([0, 1, 2, 3, 4])
That is, each index specified selects the array corresponding to the rest of the dimensions selected. In the above example, choosing 0 means that the remaining dimension of length 5 is being left unspecified, and that what is returned is an array of that dimensionality and size. It must be noted that the returned array is a view, i.e., it is not a copy of the original, but points to the same values in memory as does the original array. In this case, the 1-D array at the first position (0) is returned. So using a single index on the returned array, results in a single element being returned. That is:
x[0][2]
2
So note that x[0, 2] == x[0][2] though the second case is more inefficient as a new temporary array is created after the first index that is subsequently indexed by 2.
Note
NumPy uses C-order indexing. That means that the last index usually
represents the most rapidly changing memory location, unlike Fortran
or IDL, where the first index represents the most rapidly changing
location in memory. This difference represents a great potential for
confusion.
source
a[1][1]is more work because numpy has to create an array viewa[1]only for accessing a single element from it before the view object is thrown away (also work).getitem()call is the preferred one, there are cases where multiple calls togetitem()are difficult to express otherwise (e.g. when they are both a list of indices, or slices).