Looking at a numpy array, i find two methods to get an element from the answers given to this question: How to call an element in a numpy array?.
There are the two methods:
a[i][j] or a[i,j]
Here is a minimum reproducable example:
import numpy as np
a = np.arange(15).reshape(3, 5)
'''
array([[ 0, 1, 2, 3, 4],
[ 5, 6, 7, 8, 9],
[10, 11, 12, 13, 14]])
'''
print(a[1][1]) # returns 6
print(a[1,1]) # return 6
Both appear to give the same result, so is one method better than the other ?
>Solution :
a[1][1]
Returns the slice a[1] and then indexes that slice at [1]
a[1] -> array([5, 6, 7, 8, 9])
array([5, 6, 7, 8, 9])[1] -> 6
Whereas
a[1, 1]
Does the same end-result calculation but all within the numpy API in C, so is faster:
a[1][1]
360 ns ± 28.7 ns per loop (mean ± std. dev. of 7 runs, 1,000,000 loops each)
a[1, 1]
191 ns ± 2.76 ns per loop (mean ± std. dev. of 7 runs, 10,000,000 loops each)