Python Tutorial
NumPy Array Slicing
Slice with start:stop:step. The stop index is excluded. Slices of arrays are usually views, not copies.
1D Slices
import numpy as np
arr = np.array([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])
print(arr[1:5]) # [1 2 3 4]
print(arr[:4]) # [0 1 2 3]
print(arr[::2]) # [0 2 4 6 8]
print(arr[::-1]) # reversed2D Slices
m = np.array([[1, 2, 3, 4], [5, 6, 7, 8]])
print(m[0, 1:3]) # [2 3]
print(m[:, 1]) # second column: [2 6]
print(m[0:2, 0:2]) # top-left 2x2Step
print(arr[1:8:2]) # [1 3 5 7]Views
Changing a slice often changes the original array. Use .copy() if you need a separate block of memory (next chapters cover copy vs view).
📘 Real-World Deep Dive
Knowing <strong>NumPy Slicing (NumPy)</strong> well is what turns NumPy from a curiosity into a daily tool — you'll reach for it in nearly every real project.
Real-Life Scenario
An end-to-end usage of NumPy Slicing that you'd actually see in a data pipeline or analytics notebook.
Real-Life Example
import numpy as np
img = np.arange(36).reshape(6, 6)
patch = img[1:5, 1:5] # central 4×4
print(patch)
print("every second row:", img[::2])Expected Output
(see source)Common mistakes
- NumPy uses 0-based, C-order indexing — the rightmost axis is the *fastest-varying* one. Mixing it with Fortran-order arrays is a common surprise.
np.array([[1,2],[3,4]], dtype=int)is fine, but a ragged Python list produces dtype=object and silently disables vectorisation.- In-place ops (
a *= 2) sometimes break views instead of returning a new array; usenp.multiply(a, 2, out=...)if explicitness matters. - Treating NumPy Slicing as a black box without reading the docs — the API has subtle defaults that bite when you scale.
🚀 Performance & Best Practices
- Vectorise: replace Python
forloops with ufuncs; you can expect 10–100× speedups. - Pre-allocate output arrays with
np.emptyinstead of growing them withnp.append. - Keep data in float32 unless you need float64 precision — half the memory, double the cache locality.
- When working with NumPy, prefer vectorised / batched operations over Python loops.
🧪 Try It Yourself
- Reproduce the snippet on a representative slice of your own data.
- Profile the snippet with
cProfileortimeitand find the single biggest improvement. - Generalise the snippet into a small, reusable function you can drop into future projects.