Element-wise arithmetic works between same-shaped arrays or scalars: +, -, *, /, **. Matrix multiplication uses @ or np.dot—covered later.
Element-wise operations
import numpy as np
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
print(a + b, a * 2, b / a)
Comparison and logical
arr > 0— boolean arraynp.abs,np.sqrt,np.exp— ufuncsnp.where(cond, x, y)— element-wise choice
In-place operators
+=, *= modify arrays in place—useful but dangerous if the array is a view shared elsewhere.
Important interview questions and answers
- Q: a * b vs a @ b?
A: Star is element-wise multiply; @ is matrix multiplication (linear algebra). - Q: Scalar broadcast?
A: Adding scalar to array applies to every element without copying the scalar N times.
Self-check
- Compute element-wise square of an array.
- What ufunc gives absolute values?
Tip: Remember * is element-wise; @ is matrix multiply.
Interview prep
- * vs @?
Star element-wise; @ matrix multiplication.
- Scalar broadcast?
Scalar ops apply to every element without explicit replication.