Indexing and Slicing
Fancy Index
Four elements gathered from a 6-element list at non-contiguous positions
[0, 2, 4, 5]. The replay shows p taking each index in turn and out
growing with the selected value.
By hand
With NumPy
a[idx] accepts a list (or array) of integer positions and returns a new
array of the gathered elements in one call — no explicit loop needed. The
snapshot shows the result's shape, dtype, and values.
naive.py
values = [10, 20, 30, 40, 50, 60]
idx = [0, 2, 4, 5]
out = []
for p in idx:
out.append(values[p])
print('RESULT:', out)
library.py
import numpy as np
values = [10, 20, 30, 40, 50, 60]
idx = [0, 2, 4, 5]
a = np.array(values)
out = a[idx]
print('shape:', out.shape)
print('dtype:', out.dtype)
print('values:', out.tolist())
print('RESULT:', out.tolist())
shape: (4,)
dtype: int64
values: [10, 30, 50, 60]
RESULT: [10, 30, 50, 60]
Implementation notes
- Fancy indexing always returns a copy, not a view. Modifying the output array does not affect the original — unlike basic slicing, which returns a view.
- The index list may contain duplicates or out-of-order positions:
a[[2, 0, 2]]returns[30, 10, 30]. This flexibility is the key difference from slice syntax, which can only express contiguous or strided ranges. - Shape, dtype, and values are shown explicitly here because
ndarray.__repr__output varies with NumPy version and print options.