Indexing & Slicing (Critical for Tensors)

arr[0] is first, arr[-1] is last, arr[1:4] is elements 1–3, arr[::2] is every other. 2D arrays: matrix[row, col]. Ranges: matrix[0:2, 1:3] for a 2×2 submatrix. Master this — PyTorch and NumPy tensor operations use identical slicing syntax.

💻 Code example

import numpy as np
m = np.array([[1,2,3],[4,5,6],[7,8,9]])
print(m[0])       # [1 2 3] — first row
print(m[:, 1])    # [2 5 8] — second column
print(m[0:2, 1:3])  # [[2 3], [5 6]]

💬 Deep Dive with AI