Search code examples
pythonnumpyreshapeassignment-operator

Reshape changes assignment rules


I have this sample code where the value of 'a' is not explicitly updated in the logic of the code. Yet, when I print the output- both the variables 'a' and 'b' are updated. Can you please explain me the reason for this?

import numpy as np
a=np.ones((3,3))
N=9
a = np.reshape(a, (N, 1), 'F')

for i in np.arange(0, N, 1):
    b = np.reshape(a, (N, 1), 'F')
    b[i, 0] = a[i, 0] + 5
    print(i)
    print('a', a[i, 0])
    print('b', b[i, 0], '\n')

Output:
0
a 6.0
b 6.0 

1
a 6.0
b 6.0 

2
a 6.0
b 6.0 

3
a 6.0
b 6.0 

4
a 6.0
b 6.0 

5
a 6.0
b 6.0 

6
a 6.0
b 6.0 

7
a 6.0
b 6.0 

8
a 6.0
b 6.0 

Solution

  • b is copy of a. Because np.reshape function not necessarily returns the copy. As the documentation says:-

    This will be a new view object if possible; otherwise, it will be a copy. Note there is no guarantee of the memory layout (C- or Fortran- contiguous) of the returned array.

    If you want some way to know if yours is a copy or not then look at How can I tell if NumPy creates a view or a copy?