/Curriculum/Core NumPyLogic & Comparison

14. NumPy Logical OperationsIntermediate

Combine complex conditions using logical_and(), logical_or(), logical_not(), and & | ~ operators.

12 mins

Concept Overview

NumPy provides bitwise operators (`&`, `|`, `~`, `^`) and universal logical functions (`np.logical_and`, `np.logical_or`) to combine boolean conditions element-wise.

Hardware Mental Model

Combining conditions is like running data through two security checkpoints: `&` requires a pass from both gates; `|` lets anyone through who has either pass.

Key Concepts (1)Click snippet to load in editor

Use `&` for AND, `|` for OR, and `~` for NOT. Parentheses around each sub-expression are strictly required due to Python operator precedence.

mask = (arr > 10) & (arr < 40)

⚠ Common Mistakes & Pitfalls

Avoid these frequent beginner syntax and logic traps
❌ Incorrect:mask = arr > 10 & arr < 40 # Python executes 10 & arr first!
✓ Correct:mask = (arr > 10) & (arr < 40)

Without parentheses, `&` has higher precedence than `>` and evaluates `10 & arr` first.

Pro Tip: Always wrap every boolean condition in parentheses.

📌 Quick Revision

Core takeaway points from this topic
`&`: Element-wise logical AND.
`|`: Element-wise logical OR.
`~`: Element-wise logical NOT (inversion).
Always wrap comparison sub-expressions in parentheses.
Editor: 14. NumPy Logical 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:Filter with Combined Conditions

Given `arr = np.array([2, 8, 14, 20, 26])`, filter numbers where `(arr > 5) & (arr < 25)` and print.

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