Element-wise Operations
This is where NumPy shines. Instead of writing loops, you operate on entire arrays at once. Think of it like batch processing - much faster and cleaner.
Basic Arithmetic
All standard operators work element-wise.
import numpy as np
arr1 = np.array([1, 2, 3, 4])
arr2 = np.array([5, 6, 7, 8])
print(f"Add: {arr1 + arr2}")
print(f"Subtract: {arr1 - arr2}")
print(f"Multiply: {arr1 * arr2}")
print(f"Divide: {arr1 / arr2}")
print(f"Power: {arr1 ** 2}")
No loops needed! Each operation applies to every element. This is called vectorization.
Scalar Operations
You can operate with scalars (single numbers) too.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(f"Doubled: {arr * 2}")
print(f"Plus ten: {arr + 10}")
print(f"Modulo: {arr % 2}")
The scalar gets "broadcast" to match the array shape. We'll cover broadcasting in detail later.
Comparisons
Comparison operators return boolean arrays.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(f"Greater than 3: {arr > 3}")
print(f"Equal to 4: {arr == 4}")
print(f"Less than or equal to 2: {arr <= 2}")
One thing that confused me at first was the difference between == and np.equal. They do the same thing, but == is more Pythonic.
Try it Yourself →Key Takeaways
- Operations are element-wise by default
- No loops needed - vectorization is faster
- Scalars broadcast to match array shape
- Comparisons return boolean arrays