typestar

Views and copies in Python

Slicing gives a view; forgetting that is how numpy surprises people.

import numpy as np

original = np.arange(6)
view = original[2:5]
clone = original[2:5].copy()

view[0] = 99
clone[1] = -1

print(original)
print(view.base is original, clone.base is None)
print(np.shares_memory(original, view),
      np.shares_memory(original, clone))

How it works

  1. A basic slice shares memory with the original.
  2. copy() breaks the link deliberately.
  3. base tells you whether an array owns its data.

Keywords and builtins used here

The run, in numbers

Lines
13
Characters to type
262
Tokens
83
Three-star pace
110 tpm

At the three-star pace of 110 tokens a minute, this run takes about 45 seconds.

Type this snippet

Step 2 of 4 in Maths & memory, step 17 of 22 in NumPy.

← Previous Next →