← Back to NumPy Course | Chapter 4: Indexing & Slicing | Lesson 7 of 7

Fancy indexing

Pass a list of positions to pick several elements in any order at once.

In this page:

  1. Fancy indexing
Syntax
python
arr[[index1, index2, index3]]
matrix[[row1, row2], [col1, col2]]

Fancy indexing

Indexing with an integer array or list selects those exact positions, in the order given, and repeats are allowed. On 2-D arrays, two index arrays pick matching row and column pairs. Fancy indexing returns a copy.

Note: Use it to reorder rows: m[[2, 0, 1]].

Example: Fancy indexing

python
import numpy as np

a = np.array([10, 20, 30, 40, 50])
print(a[[0, 2, 4]])
print(a[[4, 4, 0]])
m = np.arange(9).reshape(3, 3)
print(m[[0, 1, 2], [2, 1, 0]])

# Output:
# [10 30 50]
# [50 50 10]
# [2 4 6]
Related Topics
Common Mistakes
  1. Expecting a view instead of a copy
  2. Passing a tuple where a list is needed
  3. Mismatched index array lengths
Chapter Summary
  • Index with lists or arrays of ints
  • Order and repeats are preserved
  • Returns a copy
  • Paired arrays select cells on 2-D arrays
🔒

Chapter Quiz — Complete all 7 topics to unlock

0/7 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.