Short answer
Because NumPy stores numbers in a contiguous array with a fixed type and runs the operation over all elements in a loop compiled in C, instead of handling a Python object for each element. Broadcasting is a set of rules that lets an operation apply between two arrays of different shapes without copying data.
Explanation
The broadcasting rules compare dimensions from the right: two dimensions are compatible if they are equal or one of them is 1, and the dimension of 1 is logically stretched. This lets you, for example, subtract each column's mean from a whole matrix in one line. Be careful: slicing in NumPy returns a view of the same data, not a copy, and types are fixed so a silent overflow can happen in int32. Use np.where and np.select instead of if inside loops.
Code example
import numpy as np
prices = np.array([10.0, 20.0, 30.0])
with_tax = prices * 1.14 # Without a loop
scores = np.random.rand(1000, 3) # 1000 Row × 3 columns
centered = scores - scores.mean(axis=0) # (1000,3) - (3,) ← broadcasting
labels = np.where(prices > 15, "high", "low")
view = prices[:2]
view[0] = 0
print(prices[0]) # 0.0 — view And not a copyCommon mistakes
- Using a for loop over the elements of a NumPy array, which defeats its purpose.
- Modifying a slice and assuming it is an independent copy.