Fancy Indexing Practice Problem
This data science coding problem helps you practice Indexing, Slicing & Filtering, fancy indexing, and implementation skills. Read the problem statement, write your solution, and strengthen your understanding of Indexing, Slicing & Filtering.
- Problem ID: 52
- Problem key: 52-fancy-indexing
- URL: https://datacrack.app/solve/52-fancy-indexing
- Difficulty: easy
- Topic: Indexing, Slicing & Filtering
- Module: NumPy Foundations
Problem Statement
# 🧩 Fancy Indexing
---
### 🎯 Goal
**Fancy indexing** lets you select arbitrary elements by providing a list of indices — not necessarily contiguous. This is how you randomly sample rows from a dataset, reorder features, or select the top-K elements after sorting.
---
### 🔍 How It Works
```python
arr = np.array([10, 20, 30, 40, 50])
arr[[0, 2, 4]] # → [10, 30, 50] (elements at indices 0, 2, 4)
arr[[4, 1, 3]] # → [50, 20, 40] (arbitrary order — indices control order!)
arr[[0, 0, 2]] # → [10, 10, 30] (can repeat indices)
```
---
### 💻 Task
Implement `fancy_index(data, indices)` using NumPy fancy indexing.
---
### 📥 Input
- `data`: list of elements
- `indices`: list of integers — the positions to select
### 📤 Output
- A list of elements at the specified indices, in the specified order
---
### 🧩 Starter Code
```python
import numpy as np
def fancy_index(data, indices):
"""
Select elements at specified indices using fancy indexing.
Args:
data (list): Input data
indices (list[int]): Indices to select
Returns:
list: Selected elements in the order specified by indices
"""
arr = np.array(data)
idx = np.array(indices)
# 🧠 TODO
pass
```
---
### 💡 Example
```python
fancy_index([10, 20, 30, 40, 50, 60, 70, 80, 90, 100], [0, 2, 4, 6])
# Expected: [10, 30, 50, 70]
```
---
### 🔑 Key Concepts
- **Fancy indexing picks exact positions you ask for**
Unlike slicing (`arr[1:4]`), you choose any indices in any order.
```python
arr = np.array([10, 20, 30, 40, 50])
arr[[0, 2, 4]] # [10, 30, 50]
arr[[4, 1, 3]] # [50, 20, 40]
```
* The result follows the indices list order
NumPy returns values in the same order as the indices you provide.
```python
arr = np.array([10, 20, 30, 40, 50])
arr[[4, 0, 2]] # [50, 10, 30] # index 4 first, then 0, then 2
```
* Indices can repeat values
```python
arr[[1, 1, 3]] # [20, 20, 40]
```
* `np.argsort()` gives indices that sort an array
It returns the positions of elements in sorted order.
Then fancy indexing uses those positions to rearrange the array.
```python
arr = np.array([40, 10, 30])
idx = np.argsort(arr) # [1, 2, 0]
arr[idx] # [10, 30, 40]
```Starter Code
import numpy as np
def fancy_index(data, indices):
"""
Select elements at specified indices using fancy indexing.
Args:
data (list): Input data
indices (list[int]): Indices to select
Returns:
list: Selected elements in the order specified by indices
"""
arr = np.array(data)
idx = np.array(indices)
# 🧠 TODO
pass