Indexing and Slicing
Index Element
Four corner cells of a 2×3 grid accessed by row and column index. The replay
walks a list of [i, j] coordinates, extracting i and j from each, then
reads grid[i][j] to collect the four values.
By hand
With NumPy
np.array(grid) creates a 2-D array. The comma syntax a[i, j] reads the
element at row i, column j directly — no intermediate row object needed.
The snapshot shows the array then four individual cell reads.
naive.py
grid = [[1, 2, 3], [4, 5, 6]]
coords = [[0, 0], [0, 2], [1, 0], [1, 2]]
cells = []
for coord in coords:
i = coord[0]
j = coord[1]
cells.append(grid[i][j])
print('RESULT:', cells)
library.py
import numpy as np
grid = [[1, 2, 3], [4, 5, 6]]
a = np.array(grid)
print('shape:', a.shape)
print('dtype:', a.dtype)
print('values:', a.tolist())
print('a[0, 0]:', int(a[0, 0]))
print('a[0, 2]:', int(a[0, 2]))
print('a[1, 0]:', int(a[1, 0]))
print('a[1, 2]:', int(a[1, 2]))
print('RESULT:', [int(a[0, 0]), int(a[0, 2]), int(a[1, 0]), int(a[1, 2])])
shape: (2, 3)
dtype: int64
values: [[1, 2, 3], [4, 5, 6]]
a[0, 0]: 1
a[0, 2]: 3
a[1, 0]: 4
a[1, 2]: 6
RESULT: [1, 3, 4, 6]
Implementation notes
- Python's
a[i][j]first retrieves the rowa[i](a full Python list), then indexes into it with[j]. NumPy'sa[i, j]is a single operation that computes the flat offseti * cols + jand reads one element from the contiguous buffer — the same arithmetic asreshape-1d-2d'sr * cols + c. - Shape, dtype, and values are shown explicitly here because
ndarray.__repr__output varies with NumPy version and print options.