Skip to main content
Albero Academy

Slicing

Take sub-arrays with start:stop:step per axis — and assign through slices.

Indexing & Slicing9 min

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

rows and columns
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 onward
b[::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:

in-place updates
b[:, 0] = 0 # zero out the first column
b[1, :] = [7, 8, 9] # overwrite a whole row

Key takeaways

  1. 01Slice each axis with start:stop:step (stop exclusive), separated by commas.
  2. 02b[:, 0] is a column; b[0, :] is a row; b[::2] takes every other row.
  3. 03Slices are assignable and update the array in place.
  4. 04A slice is a view sharing memory with the original — not a copy.

Finished this chapter?

Mark it complete to track your progress through NumPy.