Vectorization (NumPy)
Vectorization means expressing computations as operations on whole arrays rather than as explicit Python loops over elements. NumPy executes them in optimized C, so vectorized code is far faster and more concise.
NumPy
Instead of looping to square each number, you write a ** 2 and NumPy squares the entire array in one compiled pass. This is the central idea of NumPy: you describe what to do to all the data at once, and the library handles the iteration internally at C speed.
The performance gap is large — vectorized operations routinely run tens to hundreds of times faster than Python loops — because a loop pays Python's interpreter overhead on every element while a vectorized call pays it once. Vectorized code is also shorter and reads closer to the math.
When an operation genuinely cannot be vectorized, np.vectorize wraps a Python function for convenience, but it does not give the speed of true vectorization since it still loops internally. The real wins come from ufuncs, broadcasting, and boolean indexing.
Syntax
result = a ** 2 + b # whole-array math, no explicit loopExamples
Python
import numpy as np
a = np.array([1, 2, 3, 4])
print(a ** 2 + 1)Output:
[ 2 5 10 17]