Slicing (NumPy)
Slicing extracts a sub-section of a NumPy array using start:stop:step notation, per axis, separated by commas. Unlike list slices, a NumPy slice returns a view that shares memory with the original array.
NumPy
The syntax mirrors Python lists but extends to multiple dimensions: a[1:3, 0:2] takes rows 1–2 and columns 0–1. As usual the stop is exclusive and the step can be negative to reverse. A bare colon means 'all of this axis,' so a[:, 0] is the whole first column.
The crucial difference from Python lists is that a basic slice is a view, not a copy — writing to the slice writes through to the original array. This is great for performance but a frequent source of surprise bugs; call .copy() when you need an independent piece.
Slicing covers contiguous, regular selections. For arbitrary positions use fancy (integer) indexing, and for condition-based selection use boolean indexing — both of those return copies instead of views.
Syntax
a[start:stop:step] | a[r0:r1, c0:c1]Examples
Python
import numpy as np
print(np.arange(10)[2:7:2])Output:
[2 4 6]