Search code examples
pythonarraysnumpyshallow-copy

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.

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.