Slicing extracts a range with start:stop:step, exactly like Python lists but extended to every axis. It's how you grab a column, a block, or every other row.
Slicing per axis
b = np.array([[1, 2, 3],[4, 5, 6],[7, 8, 9]])b[:, 0] # [1 4 7] first column (all rows)b[0, :] # [1 2 3] first row (all columns)b[:2, 1:] # [[2 3] [5 6]] first 2 rows, columns 1 onwardb[::2] # every other row → rows 0 and 2
Assigning through a slice
Slices are assignable, which updates the underlying array in place — a compact way to set a whole region:
b[:, 0] = 0 # zero out the first columnb[1, :] = [7, 8, 9] # overwrite a whole row
Key takeaways
- 01Slice each axis with start:stop:step (stop exclusive), separated by commas.
- 02b[:, 0] is a column; b[0, :] is a row; b[::2] takes every other row.
- 03Slices are assignable and update the array in place.
- 04A slice is a view sharing memory with the original — not a copy.
