Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In NumPy, mathematical and comparison operators applied to arrays operate element-by-element (element-wise) by default. This contrasts with linear algebra matrix conventions (where multiplication denotes dot products) or standard Python lists (where + concatenates lists and * duplicates them).
All standard Python arithmetic operators have vectorized element-wise implementations in NumPy:
Output:
a * b is element-wise Hadamard product. It is NOT matrix multiplication. For matrix multiplication, use the @ operator or np.matmul().NumPy supports compound in-place operators (+=, -=, *=, /=), which modify the array's existing memory buffer directly without creating an intermediate array:
int_arr += 2.5 raises UFuncTypeError: Cannot cast ufunc 'add' output from dtype('float64') to dtype('int32') with casting rule 'same_kind'.Applying comparison operators (==, !=, <, <=, >, >=) evaluates each element independently, producing a boolean array:
Output:
all() and any()To evaluate whether all elements or at least one element satisfy a condition, use np.all() and np.any():
Because of IEEE 754 floating-point rounding errors, direct equality a == b is dangerous for floats. Use np.isclose() or np.allclose():
np.array([1, 2, 3]) * np.array([2, 3, 4])?arr += 5 differ from arr = arr + 5?np.any(arr < 0) evaluate to?int_arr += 1.5 on an integer array of dtype int32?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Vectorization: Eliminating Python Loops with SIMD | The Rules of NumPy Broadcasting Explained |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.