Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 49 ยท Indexing and Selection

Views vs Copies

Learn when NumPy slicing, reshape, ravel and fancy indexing return a view or a copy, how to check with base and np.shares_memory, and how to avoid surprise bugs.

NumPy is fast partly because it avoids copying data. When you slice an array, NumPy often hands you a new array object that looks at the same block of memory as the original. That new object is called a view. Change a value through the view and the original changes too. A copy, on the other hand, owns its own memory and is completely independent.

Most NumPy bugs that feel like "my data changed by itself" come from confusing the two. This lesson explains what a view really is, which operations return views and which return copies, how to check with .base and np.shares_memory, and a few safe habits. It builds on Indexing and Slicing and Fancy Indexing.

One buffer, several arrays

An array is two things: a data buffer (the raw numbers in memory) and metadata (shape, dtype, strides, offset). A view is a second piece of metadata pointing at the same buffer.

flowchart TB
    subgraph Buffer["Memory buffer"]
        M["10 | 20 | 30 | 40 | 50 | 60"]
    end
    A["a: shape (6,)"] --> M
    V["v = a[1:4]<br/>shape (3,), offset 1"] --> M
    C["c = a.copy()<br/>own buffer"] --> M2["10 | 20 | 30 | 40 | 50 | 60<br/>(separate memory)"]

The slice v shares the buffer of a; the copy c has its own.

Python A slice is a view

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Writing v[0] = -1 did not touch v only; the number lives in the shared buffer, so a[1] sees it as well.

Asking NumPy: base and shares_memory

Two tools tell you what you have.

  • arr.base is the array that owns the memory, or None if arr owns its own data.
  • np.shares_memory(x, y) answers exactly whether two arrays overlap in memory (it can be slow for complex layouts). The cheaper np.may_share_memory only compares memory bounds and may say True for arrays that merely sit inside the same range.
Python base and shares_memory

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The last two lines show the difference: even and odd use the same buffer and their memory ranges interleave, but they never touch the same elements, so shares_memory is False while the cheap may_share_memory guesses True. The base check is a good first diagnostic; shares_memory is the exact answer.

Views of views point back to the original owner. If you slice a slice, .base is still the array that really holds the data.

Which operations return what

Here is the cheat list. Memorize the pattern: anything that can be described by start, stop, step and shape changes is a view; anything that picks arbitrary elements or builds new values is a copy.

Operation Result
Basic slice a[1:5], a[::2], a[:, 0] view
a.T, np.transpose, swapaxes view
a.view() view
a.reshape(...) view when possible, otherwise copy
a.ravel() view when possible, otherwise copy
a.flatten() always a copy
Fancy indexing a[[1, 3]] copy
Boolean mask a[a > 2] copy
np.where, arithmetic, a + 1 new array (copy)
a.copy(), np.array(a) copy
Python Checking each operation

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Reshape and ravel: "view when possible"

reshape and ravel return a view if the data can be re-read in the new shape without moving anything. When the memory layout does not allow it, for example after a transpose, they quietly make a copy instead:

Python When reshape has to copy

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

This is why you should never rely on reshape or ravel giving you a view or a copy. If your code writes into the result and you need to be sure it does or does not affect the original, call .copy() explicitly or use .view() and check .base. The mechanics of memory layout come in Memory Layout and Strides.

Fancy indexing and masks always copy

Selecting with a list of integers or a boolean mask builds new data, so the result is independent:

Python Copy from a mask

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The chained-indexing trap

The difference between "read" and "write" indexing produces the most common surprise. In a[mask][0] = 1 the first part a[mask] creates a temporary copy, and the assignment lands in that temporary, which is then thrown away. The original is untouched, with no error:

Python A write that goes nowhere

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Rule of thumb: put the whole selection on the left-hand side of one assignment (a[mask] = value) instead of chaining two index operations.

Safe habits

Views are an optimization, not a bug, but you must decide deliberately which one you want.

Python Modifying a function argument

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

  • Use .copy() when you pull a slice out of a large array and want to keep only that part. A view keeps the whole parent buffer alive in memory.
  • In-place operators (+=, -=, *=, [:] =) change data through any view. That is useful for speed, but be careful when the array came from a caller.
  • When you are not sure, check np.shares_memory(x, y) or x.base.
  • If you only want to read, a view is free. If you will write and do not want side effects, copy first.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which of these returns a view of the original array?

    Basic slices describe a regular range of the same buffer, so they are views. Fancy indexing, boolean masks and flatten() always produce copies.
  2. 2. What does arr.base is None tell you?

    base points to the array that owns the memory. For an array that owns its buffer, base is None.
  3. 3. After a = np.arange(5), b = a[1:3], b[0] = 99, what is a?

    b is a view, so b[0] is the same memory as a[1].
  4. 4. Why does a[a > 3][0] = 100 leave a unchanged?

    Boolean indexing copies; the second index writes into that temporary copy, which is then discarded. Use a[mask] = value instead.
  5. 5. When should you call .copy() on a slice?

    Copying protects the original from your writes and stops a small view from keeping a huge parent buffer alive.

Summary

  • A view shares memory with another array; a copy owns its memory.
  • Basic slicing, transposes and .view() return views; fancy indexing, boolean masks, flatten(), arithmetic and .copy() return copies.
  • reshape and ravel return a view when the layout allows it and a copy otherwise, so do not depend on either.
  • Check with arr.base (owner or None) and np.shares_memory(x, y) (exact overlap).
  • Avoid chained indexing in assignments; put the whole selection on the left of one =.
  • Call .copy() before modifying a slice you do not want to link to the original.

Next, start the math part of the tutorial with Vectorized Operations and ufuncs.