/Curriculum/IntermediateSet Operations

26. NumPy Unique & Set OperationsIntermediate

Deduplicate and analyze sets with unique(), intersect1d(), union1d(), and setdiff1d().

12 mins

Concept Overview

`np.unique()` extracts unique sorted elements and can optionally return frequency counts. Set functions compute mathematical intersections and unions.

Hardware Mental Model

`np.unique(arr, return_counts=True)` is like a voting ballot tally box: it counts the distinct candidates and how many votes each candidate received.

Key Concepts (1)Click snippet to load in editor

`np.unique(arr, return_counts=True)` returns a tuple: (unique_elements, counts).

vals, counts = np.unique(arr, return_counts=True)

⚠ Common Mistakes & Pitfalls

Avoid these frequent beginner syntax and logic traps
❌ Incorrect:list(set(arr)) # Destroys array typing and returns unsorted Python set
✓ Correct:np.unique(arr) # Returns sorted ndarray

`np.unique()` returns a typed ndarray and is much faster than round-tripping through Python's `set()`.

Pro Tip: Use `np.unique(arr)` directly on ndarrays.

📌 Quick Revision

Core takeaway points from this topic
`np.unique(arr)`: Returns sorted distinct elements.
`return_counts=True`: Returns counts of each unique item.
`np.intersect1d(a, b)`: Elements present in both arrays.
`np.union1d(a, b)`: Combined unique elements from both arrays.
`np.setdiff1d(a, b)`: Elements in `a` that are not in `b`.
Editor: 26. NumPy Unique & Set Operations
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:Find Common Elements (intersect1d)

Create `a = np.array([10, 20, 30])` and `b = np.array([20, 30, 40])`, find intersection with `np.intersect1d(a, b)`, and print.

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