/Curriculum/Core NumPyLogic & Comparison

13. NumPy Comparison OperationsBeginner

Element-wise comparison operators ==, !=, >, <, >=, <= producing boolean arrays.

10 mins

Concept Overview

Comparison operators evaluate each element against a scalar or matching array, returning a boolean array of True/False values.

Hardware Mental Model

Comparing an array is like asking a question to every student in a classroom: each student holds up a True card or a False card.

Key Concepts (1)Click snippet to load in editor

Evaluating `arr > 30` creates an ndarray of dtype bool with identical shape.

is_greater = arr > 30

⚠ Common Mistakes & Pitfalls

Avoid these frequent beginner syntax and logic traps
❌ Incorrect:if arr > 10: print('All greater') # ValueError: The truth value is ambiguous
✓ Correct:if (arr > 10).all(): print('All greater')

An array of booleans cannot be evaluated by Python's `if`. Use `.all()` or `.any()`.

Pro Tip: Use `arr.all()` to check if every element is True; use `arr.any()` if at least one is True.

📌 Quick Revision

Core takeaway points from this topic
Comparison operators return boolean ndarrays.
`arr.all()` checks if all values are True.
`arr.any()` checks if any value is True.
`np.sum(bool_arr)` counts the number of True occurrences.
Editor: 13. NumPy Comparison 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:Evaluate Array Greater Than

Create `arr = np.array([5, 15, 25])`, evaluate `arr >= 15`, and print the resulting boolean array.

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