/Curriculum/IntermediateSearching & Sorting

23. NumPy SearchingIntermediate

Locate elements and indices using np.where(), np.nonzero(), and np.searchsorted().

14 mins

Concept Overview

`np.where(condition, [x, y])` returns indices where condition is True, or performs ternary `if-else` element selection across arrays.

Hardware Mental Model

`np.where(condition, x, y)` is a vectorized ternary operator: 'If condition is True pick from x, otherwise pick from y'.

Key Concepts (1)Click snippet to load in editor

1. `np.where(cond)`: Returns a tuple of coordinate index arrays. 2. `np.where(cond, x, y)`: Vectorized if-else replacement.

idx = np.where(arr == 30); new_arr = np.where(arr < 0, 0, arr)

⚠ Common Mistakes & Pitfalls

Avoid these frequent beginner syntax and logic traps
❌ Incorrect:idx = np.where(arr > 20); print(idx) # Returns tuple: (array([1, 2]),)
✓ Correct:idx = np.where(arr > 20)[0] # Extract the 1D index array

`np.where(condition)` returns a tuple containing index arrays for each dimension.

Pro Tip: Use `np.where(condition)[0]` for 1D arrays to get the clean index vector.

📌 Quick Revision

Core takeaway points from this topic
`np.where(cond)`: Finds matching coordinate indices.
`np.where(cond, x, y)`: Vectorized ternary if-else.
`np.nonzero(arr)`: Returns indices of non-zero elements.
`np.searchsorted(arr, v)`: Binary search for sorted insertion indices.
Editor: 23. NumPy Searching
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state

🎯 Try It Yourself: Practice Challenge

Hands-on Mode

Solve the objective below using NumPy vectorized syntax

Objective:Replace Negative Numbers with Zero

Given `arr = np.array([-5, 10, -15, 20])`, use `np.where(arr < 0, 0, arr)` and print the result.

Expected Output Target:[ 0 10 0 20]
Practice Workspace
Python ● Ready
Initializing Python IDE...
Ctrl+Enter
Execution Result
Click "RUN CODE" to execute and inspect array state