Fancy Indexing (NumPy)

Fancy indexing selects elements from a NumPy array by passing an array or list of integer positions, letting you pick arbitrary, non-contiguous elements in any order. Unlike a slice, it returns a copy, not a view.

NumPy

Where slicing can only take regular ranges, fancy indexing takes exactly the positions you list: a[[0, 2, 3]] returns the 1st, 3rd, and 4th elements, and a[[2, 0, 1]] even reorders them. You can repeat indices to duplicate elements.

In multiple dimensions you supply an index array per axis, and they pair up element-wise: a[[0, 1], [2, 3]] returns a[0, 2] and a[1, 3]. This is powerful but trips people up, since it pairs positions rather than forming a grid (use np.ix_ for the grid behavior).

Because it gathers scattered elements, fancy indexing always produces a new copy, so you can safely modify the result. It also works on the left side of an assignment to scatter values into specific positions.

Syntax

a[[i0, i1, i2]]  |  a[row_idx, col_idx]

Examples

Python

import numpy as np
a = np.array([10, 20, 30, 40])
print(a[[0, 2, 3]])

Output:

[10 30 40]

Learn it in a lesson

See also

Back to the Dictionary