12.3.2.4. Copy

import numpy as np


a = np.array([[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]])

No new object is created!

b = a
b is a

Out:

True

unique identifier of an object

def f(x):
    print(id(x))

id(a)

Out:

2212782046640
f(a)

Out:

2212782046640

View and shallow copy

c = a.view()
c is a

Out:

False

c is a view of the data owned by a

c.base is a

Out:

True
c.flags.owndata

Out:

False

shape of a doesn’t change

c = c.reshape((2, 6))

a’s data changes

c[0, 4] = 1234
a

Out:

array([[   0,    1,    2,    3],
       [1234,    5,    6,    7],
       [   8,    9,   10,   11]])

Slicing an array returns a view of it

s = a[:, 1:3]
s

Out:

array([[ 1,  2],
       [ 5,  6],
       [ 9, 10]])

Deep copy

d = a.copy()
d is a

Out:

False
d.base is a

Out:

False

Total running time of the script: ( 0 minutes 0.004 seconds)

Gallery generated by Sphinx-Gallery