Loading Page Content...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
Preparing courses, live labs, and learning resources.सामग्री लोड हो रही है, कृपया प्रतीक्षा करें...
In standard programming languages, iterating over collections with for or while loops is the default way to process data. In numerical computing with Python, however, explicit loops are the single greatest source of performance degradation.
Vectorization is the practice of replacing explicit Python-level element-by-element loops with high-level array expressions that delegate batch operations directly to compiled, low-level C and Fortran routines.
When you execute a loop like:
The Python virtual machine must perform significant overhead on every single iteration:
x and y.__add__ dunder method on x.PyObject, perform addition, and box the result into a newly allocated heap object.When you write:
NumPy executes a single, compiled loop in C:
Let's measure the concrete speed difference between a standard Python loop and a vectorized NumPy operation across 1,000,000 numbers:
Typical Benchmark Output:
Calculating the Euclidean distance $d = \sqrt{(x_2 - x_1)^2 + (y_2 - y_1)^2}$ across $100,000$ coordinate pairs:
Estimating $\pi$ by sampling $10,000,000$ random points in the unit square:
for loops inherently slower than NumPy array operations?a and b of length 1,000,000, which approach is recommended?Continue learning with hands-on practice, examples, and exercises in the upcoming topic.
| Previous Lesson | Next Lesson |
|---|---|
| Splitting Arrays into Chunks (split, hsplit, vsplit) | Element-Wise Arithmetic & Comparison Operations |
Test your understanding of this lesson with 5 questions. Each question has one correct answer.