Knowing why NumPy is fast lets you keep it fast. The essentials: arrays are one contiguous block of memory, many operations return cheap views rather than copies, and staying vectorised avoids the Python-loop tax. A little awareness here turns slow code quick.
How arrays sit in memory
An ndarray is a flat contiguous buffer plus strides that describe how to step through it. That layout is why a reshape or transpose can be free — only the strides change, not the data:
a = np.arange(12).reshape(3, 4)a.strides # bytes to step per dimensiona.flags['C_CONTIGUOUS'] # row-major layout?a.nbytes # total bytes useda.T.flags['C_CONTIGUOUS'] # False — transpose is a view with swapped strides
Views vs copies revisited
Slices and reshapes usually return a view (shares memory, free); fancy indexing and .copy() return a new array. Knowing which you have prevents both bugs and wasted memory:
a = np.arange(10)s = a[2:6] # view — shares memorys.base is a # True → confirms it's a viewf = a[[2, 3, 4]] # fancy index — a copyf.base is None # True → independenta.reshape(2, 5).base is a # True → reshape is (usually) a view
In-place operations
a += 1 modifies the existing buffer; a = a + 1 allocates a whole new array. For large arrays in tight loops, in-place ops and the out= parameter save real time and memory:
a *= 2 # in place — no new arraynp.multiply(a, 2, out=a) # explicit in-place via out=np.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
Practice
Take a slice and a fancy-index of the same array; use .base to prove one is a view and the other a copy. Rewrite a Python loop that squares and sums an array as a single vectorised expression and compare. Convert an a = a + 1 to an in-place a += 1 and explain the memory difference.
Key takeaways
- 01An ndarray is a contiguous buffer plus strides — so reshape/transpose can be free (view only).
- 02Slices and reshapes usually return views (shared memory); fancy indexing and .copy() allocate.
- 03Check .base to tell a view from a copy — avoids both aliasing bugs and wasted memory.
- 04In-place ops (a += 1, out=) reuse the buffer instead of allocating a new array.
- 05Replace element-wise Python loops with vectorised expressions for 10–100× speedups.
