I'm a relatively new programmer and I was just wondering the best practice for accessing a certain row and column. From what I know both below work.
array[r,c]
array[r][c]
However, I've read that array[r,c]
is better practice in general. Could someone tell me if I am correct and if so why as well as how it applies to higher-dimension arrays? Thank you so much for helping out a newcomer!
CodePudding user response:
tl;dr: array[r,c]
is faster than array[r][c]
Let compare the performance of two methods. I prepared a 2D array as follow:
import numpy as np
array = np.random.rand(1000, 1000)
Then I compared the speed of two methods:
%timeit array[42, 42]
The output is:
221 ns ± 7.86 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
and for the other method:
%timeit array[42][42]
Output:
436 ns ± 8.28 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
It is obvious array[r,c] is faster than array[r][c]
. I think that is because in the array[r][c]
approach, first array[r]
will be calculated and returned. For the sake of argument, call this result row=array[r]
. Then once again, row[c]
will be calculated and returned.