Answer to Question #187618 in Python for Tanmay

Question #187618

import numpy as np

old = no.array([[1, 1, 1], [1, 1, 1]])

new = old

new[0, :2] = 0

print(old)


1
Expert's answer
2021-04-30T17:36:37-0400

(i) There is a typo in the second line, it should be

old = np.array([[1, 1, 1], [1, 1, 1]])

(ii) The script returns the array

[[0 0 1]

 [1 1 1]].

This happens in python for memory optimization purposes. Line tree (new=old) creates a pointer that points to the same memory address and to the same object in memory. Then, when we change some values in new, we change the only one unique object shared for new and old, so when old is printed it is changed too.

To avoid this, two separate arrays are needed. This is called a deep copy. A copied array in this case will be a totally different object stored in another memory cell.

from copy import deepcopy
import numpy as np

old = np.array([[1, 1, 1], [1, 1, 1]])

new = deepcopy(old)

new[0, :2] = 0

print(old)

will print

[[1 1 1]
 [1 1 1]]

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

Comments

No comments. Be the first!

Leave a comment

LATEST TUTORIALS
New on Blog
APPROVED BY CLIENTS