Moon Zoe Moon Zoe - 2 years ago 164
Python Question

array assignment using slicing

When I was using array assignment using slicing, there is some thing strange happened. The source code is below:

import numpy as np
a = np.array([1,2,3,4]).reshape(2,2)
b = np.array([5,6,7,8]).reshape(2,2)
b = a[:]
b[1,1] = 10
print(b is a)

The result is given as:

enter image description here

From the result, the id of b and a is different after array assignment, but when I change the value of b, the value in a also changed. Why is this?

Using Sublime Text, Python 3.4.3.

Answer Source

With lists, b=a[:] makes a copy of a. Changes to b will not affect a or its values.

But with an numpy array, this action makes view. b is a new object, but it shares the underlying data buffer. Changes to values in b will affect a.

Use b=b.copy() is you want a true copy.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download