Indexing and Slicing
Slice 2D Row and Column
Row 0 and column 1 extracted from a 2×3 grid. The trace shows row assigned
directly from grid[r], then a loop building col by pulling one element per
row at the fixed column index c.
By hand
A row is just grid[r] — Python returns the inner list directly. A column
requires a loop: for each row index i, read grid[i][c] and append to
col.
naive.py
Replay: real traced execution (multi-file project)
grid = [[1, 2, 3], [4, 5, 6]]
r = 0
c = 1
row = grid[r]
col = []
for i in range(len(grid)):
col.append(grid[i][c])
print('RESULT:', (row, col))
grid ← [[1, 2, 3], [4, 5, 6]]
1grid = [[1, 2, 3], [4, 5, 6]]2r = 0values this step[[1, 2, 3], [4, 5, 6]]gridr ← 0
1grid = [[1, 2, 3], [4, 5, 6]]2r = 03c = 1values this step0rc ← 1
2r = 03c = 14row = grid[r]values this step1crow ← [1, 2, 3]
3c = 14row = grid[r]5col = []values this step[1, 2, 3]rowcol ← []
4row = grid[r]5col = []6for i in range(len(grid)):values this step[]coli ← 0
5col = []6for i in range(len(grid)):7 col.append(grid[i][c])values this step0icol ← [2]
6for i in range(len(grid)):7 col.append(grid[i][c])8print('RESULT:', (row, col))values this step[] → [2]coli ← 1
5col = []6for i in range(len(grid)):7 col.append(grid[i][c])values this step0 → 1icol ← [2, 5]
6for i in range(len(grid)):7 col.append(grid[i][c])8print('RESULT:', (row, col))values this step[2] → [2, 5]colfor i in range(len(grid)):
5col = []6for i in range(len(grid)):7 col.append(grid[i][c])stdout ← RESULT: ([1, 2, 3], [2, 5])
7 col.append(grid[i][c])8print('RESULT:', (row, col))values this stepRESULT: ([1, 2, 3], [2, 5])stdout
With NumPy
a[r, :] selects all columns of row r (the : means "every index along
this axis"). a[:, c] selects all rows of column c. The snapshot shows the
full array then each extraction labeled by its slice expression.
library.py
import numpy as np
grid = [[1, 2, 3], [4, 5, 6]]
a = np.array(grid)
r, c = 0, 1
row = a[r, :]
col = a[:, c]
print('shape:', a.shape)
print('dtype:', a.dtype)
print('values:', a.tolist())
print(f'a[{r}, :]: shape: {row.shape} dtype: {row.dtype} values: {row.tolist()}')
print(f'a[:, {c}]: shape: {col.shape} dtype: {col.dtype} values: {col.tolist()}')
print('RESULT:', (row.tolist(), col.tolist()))
shape: (2, 3)
dtype: int64
values: [[1, 2, 3], [4, 5, 6]]
a[0, :]: shape: (3,) dtype: int64 values: [1, 2, 3]
a[:, 1]: shape: (2,) dtype: int64 values: [2, 5]
RESULT: ([1, 2, 3], [2, 5])
Implementation notes
- Axis 0 runs along rows (top to bottom); axis 1 runs along columns (left to
right).
a[r, :]holds axis 0 fixed and ranges over axis 1;a[:, c]is the reverse. - Both
a[r, :]anda[:, c]return views, not copies — the same rule as basic slicing. A column extracted this way shares memory with the original array. - Shape, dtype, and values are shown explicitly here because
ndarray.__repr__output varies with NumPy version and print options.