Latticework

Command Palette

Search for a command to run...

NumPy

Indexing & Slicing

15 min

Explanation

NumPy slicing extends Python's list[start:stop:step] syntax to any number of dimensions, and — unlike a Python list slice — an array slice is a view into the original data, not a copy.

import numpy as np

arr = np.array([10, 20, 30, 40, 50])
print(arr[1:4])    # [20 30 40]
print(arr[::-1])    # [50 40 30 20 10] — reversed
print(arr[::2])      # [10 30 50] — every other element
Try it

grid[row, col] with a comma is NumPy's multi-dimensional indexing — very different from Python's nested-list grid[row][col], and much more powerful for slicing.

Loading editor…
Explanation

Boolean masking is how you filter an array without writing a loop — compare the array to get a True/False array, then index with it:

temps = np.array([68, 72, 55, 90, 61])
hot = temps[temps > 70]     # [72 90] — only the elements where temps > 70 was True
temps[temps < 60] = 60       # clip: replace every element under 60 with 60

Because array slices are views (not copies), arr[1:4] = 0 mutates the original array — if you need an independent copy, call .copy() explicitly. Boolean masking (arr[mask]) does return a copy, so this particular gotcha doesn't apply there.

Exercise

Write `every_other(arr)`, returning every other element of `arr` starting at index 0, using slicing (`arr[::2]`).

Exercise

Write `mask_positive(arr)`, returning only the positive elements of `arr`, using boolean masking (`arr[arr > 0]`) — not a loop or list comprehension.

Quiz

What does `arr[arr > 0]` do?

Checkpoint

You can slice arrays (including multi-dimensional), and filter them with boolean masks instead of a loop.