0

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 
Ankit Bansal
  • 317
  • 4
  • 14
  • Copy the array to make sure. `b = np.reshape(a, (N, 1), 'F').copy()` – klim Nov 01 '18 at 09:33
  • `reshape` usually produces a `view`, not a copy. The distinction is important in numpy and needs careful reading in the docs. – hpaulj Nov 01 '18 at 11:09

2 Answers2

1

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?

jimmy
  • 496
  • 5
  • 13
0

I tried the following thing and it works

 a=np.ones((3,3))
 N=9
 print(a)
 b=np.ones((3,3))
 b = a+5
Anuprita
  • 33
  • 1
  • 7