Array Arithmetic and Broadcasting
In NumPy, you can perform mathematical operations directly on arrays — no loops required.
This approach is known as element-wise computation, and it’s both efficient and concise.
Array Arithmetic
When two arrays have the same size, NumPy applies operations element by element.
Array Arithmetic
a = np.array([1, 2, 3])
b = np.array([10, 20, 30])
print(a + b) # [11 22 33]
print(a * b) # [10 40 90]
You can also subtract, divide, or raise to powers: a - b, a / b, a ** 2
Broadcasting
When arrays have different shapes, NumPy uses broadcasting to automatically align them.
Smaller arrays are conceptually “stretched” across the larger ones so the operation can be applied seamlessly.
Broadcasting Example
a = np.array([1, 2, 3])
b = 10
print(a + b) # [11 12 13]
NumPy adds 10 to each element in a.
Broadcasting can also work between 2D and 1D arrays in many cases, which you will practice later.
Summary
- Use
+,-,*,/,**directly on arrays - Operations are applied element by element
- Broadcasting enables operations between arrays of different shapes
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.