0

Sorry if I asked a stupid question. I cannot understand the following codes in python. Why my operations on the "new" array also work on the "old" array?

import numpy as np
old = np.array([[1, 1, 1], [1, 1, 1]])
new = old
new[0, :2] = 0
new==old

output is "TRUE".

I have been using MATLAB for years and just recently start to learn Python. This is totally different from Matlab. And I cannot comprehend the above codes and ask if there is any deep reason for such a result. Thanks a million!

  • This is because of pass by reference. – GreatThinker Mar 15 '21 at 12:40
  • you have to use deepcopy for expected behavior `new = deepcopy.copy(old)` – GreatThinker Mar 15 '21 at 12:41
  • @GreatThinker Thanks a lot! I have been struggling a lot about this. I will check more about the "pass by reference". – bright bot Mar 15 '21 at 12:50
  • 3
    @Great, `new=old.copy()` is sufficient. – hpaulj Mar 15 '21 at 12:52
  • Does this answer your question? [What is the difference between shallow copy, deepcopy and normal assignment operation?](https://stackoverflow.com/questions/17246693/what-is-the-difference-between-shallow-copy-deepcopy-and-normal-assignment-oper) – mtrw Mar 15 '21 at 14:46
  • @brightbot - this issue of shallow and deep copies is something that often confuses people that are new to Python, so it's a good question. I've marked your question as a duplicate in an effort to be helpful to both you and other people searching for the same information. Also, as someone who already know MATLAB, you may find this extremely helpful: https://numpy.org/doc/stable/user/numpy-for-matlab-users.html – mtrw Mar 15 '21 at 14:49
  • @mtrw, when working with `numpy`, `deepcopy` is usually not needed. The distinction between simple variable assignment and copy on assignment is what's important here. `numpy` does have something in between, a `view`, which the OP will eventually have to understand. – hpaulj Mar 15 '21 at 17:42
  • @hpaulj - yeah, a better canonical assignment/copy/view answer for NumPy would be nice here. I didn't see a good one in a quick search, can you suggest something? – mtrw Mar 16 '21 at 15:42

0 Answers0