Numpy: Difference between a[i][j] and a[i,j]

2020-06-09 04:02发布

问题:

Coming from a Lists background in Python and that of programming languages like C++/Java, one is used to the notation of extracting elements using a[i][j] approach. But in NumPy, one usually does a[i,j]. Both of these would return the same result.

What is the fundamental difference between the two and which should be preferred?

回答1:

The main difference is that a[i][j] first creates a view onto a[i] and then indexes into that view. On the other hand, a[i,j] indexes directly into a, making it faster:

In [9]: a = np.random.rand(1000,1000)

In [10]: %timeit a[123][456]
1000000 loops, best of 3: 586 ns per loop

In [11]: %timeit a[123,456]
1000000 loops, best of 3: 234 ns per loop

For this reason, I'd prefer the latter.