Skip to main content
MahiDev — Learn. Build. Become AI-ready.

Lesson 07

Advanced Indexing

Pick scattered values with index lists: chosen positions in 1-D, row and column pairs in 2-D, sub-grids with ix_, and positions in 3-D arrays.

Intermediate25 min
Advanced Indexing hero Module 23 Lesson 7

A slice can only take evenly spaced positions. To pick scattered values, pass a list or an array of indices instead. This is called advanced, or fancy, indexing. It always returns a new array.

A 3 by 4 array with two scattered values picked by index pairs

1-D: a list of positions

Put the positions in a list, or in an ndarray, and pass it inside the brackets. Positions can repeat and can be negative.

python
import numpy as np

a = np.array([40, 15, 72, 8, 63, 27, 90, 51])
print(a[[0, 3, 7]])

picks = np.array([0, -2, -1])
print(a[picks])
print(a[[2, 2, 0]])

Output:

text
[40  8 51]
[40 90 51]
[72 72 40]

2-D: row and column pairs

m[rows, cols] with two lists reads them as pairs. The first row goes with the first column, the second row with the second column. Tuples work the same way as lists.

python
import numpy as np

m = np.array([[11, 12, 13, 14],
              [21, 22, 23, 24],
              [31, 32, 33, 34]])
print(m[[0, 2], [1, 3]])
print(m[(0, 1, 2), (0, 1, 2)])

Output:

text
[12 34]
[11 22 33]

Whole rows and sub-grids

One list picks whole rows, in the order you give. To keep every combination of chosen rows and chosen columns, wrap both lists in np.ix_.

python
import numpy as np

m = np.array([[11, 12, 13, 14],
              [21, 22, 23, 24],
              [31, 32, 33, 34]])
print(m[[2, 0]])
print(m[np.ix_([0, 2], [1, 3])])

Output:

text
[[31 32 33 34]
 [11 12 13 14]]
[[12 14]
 [32 34]]

3-D positions

Give one list for blocks, one for rows, and one for columns. Each position reads one value from the lists at the same place.

python
import numpy as np

t = np.arange(1, 19).reshape(2, 3, 3)
print(t[[0, 1], [1, 2], [2, 0]])

Output:

text
[ 6 16]

The result is a copy

Unlike a slice, advanced indexing builds a new array. Changing the result leaves the original alone.

python
import numpy as np

a = np.array([5, 6, 7, 8])
picked = a[[0, 1]]
picked[0] = -1
print(picked)
print(a)

Output:

text
[-1  6]
[5 6 7 8]

Key takeaways

  • Pass a list of positions to pick scattered values

  • Two lists in 2-D are read as row and column pairs

  • np.ix_ keeps every chosen row and column combination

  • Advanced indexing returns a copy

  • Next: Copy and View

  • Previous: Slicing

Loading playground…

Check your understanding

Advanced Indexing Quiz

What does np.array([5, 6, 7])[[0, 2]] give?

1 / 10