Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Creating numpy shallow copies with arithmetic operations

I noticed that array operations with an identity elements return a copy (possibly a shallow copy) of the array.

Consider the code snippet below.

a=np.arange(16).reshape([4,4])
print(a)
b=a+0
print(b)
a[2,2]=200
print(a)
print(b)

We see that b is a shallow copy of a. I don’t know if it is a deep copy, because I think matrix is a subtype of array, rather than array of arrays.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

If I only need a shallow copy,

  • Is there a difference between using np.copy() and arithmetic operations?
  • Is b=a+0 or b=a*1 a bad practice? If it is, why?

I know this is a frequently asked topic, but I couldn’t find an answer for my particular question.

Thanks in advance!

>Solution :

Is there a difference between using np.copy() and arithmetic
operations?

Yes, consider following example

import numpy as np
arr = np.array([[True,False],[False,True]])
arr_c = np.copy(arr)
arr_0 = arr + 0
print(arr_c)
print(arr_0)

output

[[ True False]
 [False  True]]
[[1 0]
 [0 1]]

observe that both operations are legal (did not cause exception or error) yet give different results.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading