Knowing why NumPy is fast lets you keep it fast. The essentials: arrays are one contiguous memory block, many operations return cheap views, and staying vectorised avoids the Python-loop tax.
In-place operations
a += 1 reuses the existing buffer; a = a + 1 allocates a whole new array. For large arrays this matters:
a *= 2 # in place — no new arraynp.sqrt(a, out=a) # write the result back into a
Vectorise, don't loop
# Slow: Python looptotal = 0for x in a:total += x * x# Fast: vectorisedtotal = (a * a).sum() # or a @ a
Key takeaways
- 01An ndarray is a contiguous buffer, so slices/reshape can be cheap views.
- 02In-place ops (a += 1, out=) reuse the buffer instead of allocating a new array.
- 03Replace element-wise Python loops with vectorised expressions for 10–100× speedups.
- 04Views share memory (fast); copies allocate — know which you have.
