0

I am assigning the array x to the array x2 and x3 but the operations do not result in anything and my final x2 and x3 are the same as x

x = np.random.randint(10, size=100)
x2 = x 
x3 = x

for i in range(1,x.shape[0]-1):
   x2[i] = (x[i-1]+x[i+1])/2

for i in range(3,x.shape[0]-3):
    x3[i] = (x[i-2]+x[i-1]+x[i+1] + x[i+2])/4  

1 Answers1

0

Use the copy method on numpy arrays:

x2 = x.copy()
x3 = x.copy()
Chrysophylaxs
  • 5,818
  • 3
  • 10
  • 21
  • Thank you! It works! Do you know the reason it does not work originally? – AkashSngh Oct 05 '22 at 17:34
  • 1
    Take a look here: https://stackoverflow.com/questions/68060806/assigning-complex-mutable-variables-in-python-by-value, and similar posts. In short, when you assign a new variable to a complex/mutable type, it only assigns the new variable to a reference of the original object. In your case, `x`, `x2`, and `x3` are all different variables, but they all refer to the same np array object in memory. As such, when you change that memory by editing `x`, the changes are shown in `x2` and `x3` too, since they refer to the same memory. – Chrysophylaxs Oct 05 '22 at 17:53