NumPy Memory Views — ELI5
Imagine two people looking through different windows at the same garden. Person A sees the rose bushes. Person B sees the vegetable patch. They are looking at the same garden, just from different angles. Neither person made a copy of the garden — there is only one garden.
NumPy works the same way. When you slice an array — say, grab rows two through five — NumPy does not copy those rows into a new block of memory. Instead, it creates a view: a new window that points at the same data from a different angle.
This is why NumPy is so fast. Copying a million numbers takes time and memory. Pointing at the same million numbers takes almost no time and no extra memory.
But there is a catch. If person A plants a tree in the garden, person B sees it too. Similarly, if you change data through a view, the original array changes as well. That surprises people who expected slicing to give them a safe, independent copy.
The fix is simple: if you want a truly separate copy, call .copy(). Now you have two gardens, and changes to one do not affect the other.
Most NumPy operations — slicing, transposing, reshaping — create views. Operations like fancy indexing (using a list of specific positions) create copies. Knowing which is which saves you from confusing bugs.
The one thing to remember: A view is a different window into the same data — fast and free, but changes through one window affect the original.
See Also
- Python Bokeh Get an intuitive feel for Bokeh so Python behavior stops feeling unpredictable.
- Python Numpy Advanced Indexing How to cherry-pick exactly the data you want from a NumPy array using lists, masks, and fancy tricks.
- Python Numpy Broadcasting Rules How NumPy magically makes different-sized arrays work together without you writing any loops.
- Python Numpy Einsum One tiny function that replaces dozens of NumPy operations — once you learn its shorthand, array math becomes a breeze.
- Python Numpy Fft Spectral How NumPy breaks apart a signal into its hidden frequencies — like separating a chord into individual notes.