Skip to main content
Albero Academy

Fancy Indexing

Select arbitrary elements with arrays of indices, in any order.

Indexing & Slicing8 min

Basic slicing takes contiguous ranges. Fancy indexing passes an array of indices to grab arbitrary elements in any order, as many times as you like — how you reorder, sample and gather scattered values without a loop.

Picking any elements

integer array indexing
a = np.array([10, 20, 30, 40, 50])
a[[0, 2, 4]] # [10 30 50] pick these positions
a[[4, 4, 0]] # [50 50 10] repeats & order allowed
m = np.arange(12).reshape(4, 3)
m[[3, 0, 1]] # rows reordered

Selecting by coordinates

Pass one index array per dimension to pull out specific (row, col) pairs:

(row, col) pairs
m = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])
rows = [0, 1, 2]
cols = [2, 0, 1]
m[rows, cols] # [3 4 8] → (0,2), (1,0), (2,1)

Key takeaways

  1. 01Fancy indexing passes an array of indices to grab arbitrary elements in any order (repeats allowed).
  2. 02One index array per dimension selects specific (row, col) coordinate pairs.
  3. 03It works on the left of = to write scattered positions too.
  4. 04Fancy indexing returns a copy, not a view.

Finished this chapter?

Mark it complete to track your progress through NumPy.