📡 You're offline — showing cached content
New version available!
Quick Access
Tutorials NumPy Array Indexing and Slicing

Array Indexing and Slicing

5 min read Quiz at the end
Index with integers, slices, boolean masks, and fancy indexing to select array elements.

Indexing and Slicing

import numpy as np
a = np.array([[1,2,3],[4,5,6],[7,8,9]])

# Basic indexing
a[0]         # first row: [1 2 3]
a[0, 1]      # row 0, col 1: 2
a[-1]        # last row: [7 8 9]

# Slicing [start:stop:step]
a[0:2]       # rows 0 and 1
a[:, 1]      # all rows, column 1: [2 5 8]
a[0:2, 1:3]  # rows 0-1, cols 1-2
a[::2]       # every other row

# Boolean indexing
a[a > 5]     # elements greater than 5
a[a % 2 == 0]  # even elements

# Fancy indexing
idx = [0, 2]
a[idx]       # rows 0 and 2