1

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)
print(id(a))
print(id(b))
b = a[:]
b[1,1] = 10
print(b is a)
print(id(a))
print(id(b))
print(a)
print(b)

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.

Moon Zoe
  • 53
  • 4
  • That link is about lists. This question is about `numpy` arrays. – hpaulj Jun 17 '16 at 14:33
  • 2
    `a[:]` makes a `view` not a copy. – hpaulj Jun 17 '16 at 14:34
  • @hpaulj Thank you. You are right. Numpy array is different from list. – Moon Zoe Jun 17 '16 at 14:57
  • I removed the `duplicates` because this is about an array view v copy, not about list copies and deep copies. http://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list-in-python. **`numpy` arrays are not lists** – hpaulj Jun 17 '16 at 23:57

2 Answers2

1

I think you might have an issue with referencing (b=a[:]). Here is a previous answer that might help:

Python objects confusion: a=b, modify b and a changes!

Community
  • 1
  • 1
janeDoe
  • 11
  • 1
0

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.

https://docs.scipy.org/doc/numpy-dev/user/quickstart.html#copies-and-views

hpaulj
  • 221,503
  • 14
  • 230
  • 353
  • This is the file I found, exactly what you said.[docs.scipy.org/doc/numpy-dev/user/quickstart](https://docs.scipy.org/doc/numpy-dev/user/quickstart.html) – Moon Zoe Jun 17 '16 at 15:22