Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In NumPy terminology, Fancy Indexing refers to indexing an array using arrays or sequences of integer indices rather than basic integer scalars or slice objects (start:stop:step).
While basic slicing allows you to extract regularly spaced sub-grids, fancy indexing provides complete freedom to access, reorder, or duplicate arbitrary elements across any dimension.
To select elements at non-contiguous positions, pass a Python list or NumPy array of integers representing the desired target indices:
Output:
When working with 2D or N-dimensional matrices, fancy indexing allows row selection, column selection, or simultaneous point-coordinate extraction.
When you pass two integer arrays matrix[rows, cols], NumPy pairs the indices element-by-element like coordinates (r0, c0), (r1, c1), (r2, c2), rather than taking a cross-product matrix:
Output:
If you instead want a rectangular sub-grid (the cross-product of those rows and columns), combine integer slicing with np.ix_():
This is one of the most vital architectural rules in NumPy:
| Indexing Technique | Memory Behavior | Modification Effect |
|---|---|---|
Basic Slicing (arr[1:4]) | Returns a VIEW (shared memory buffer) | Modifying view mutates original array |
Fancy Indexing (arr[[1, 4]]) | Returns a COPY (new memory allocation) | Modifying copy has NO effect on original |
Boolean Masking (arr[arr > 0]) | Returns a COPY (new memory allocation) | Modifying copy has NO effect on original |
Even though reading with fancy indexing yields a copy, assigning to fancy-indexed positions modifies the original array in-place:
If an index appears multiple times during in-place assignment, the assignment happens sequentially, but with operators like +=, repeated increments might only execute once unless you use np.add.at():
matrix = np.arange(16).reshape(4, 4), what is the output of matrix[[0, 1], [2, 3]]?arr = np.array([10, 20, 30]) and you execute idx = [0, 1]; sub = arr[idx]; sub[0] = 99, what is the value of arr[0]?counter[[0, 0, 0]] += 1 fail to increment counter[0] by 3?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Boolean Masking & Conditional Filtering | Conditional Selectors: np.where(), np.select() & np.extract() |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.