1

This is my code

import numpy as np
v = np.zeros(4)
backup = np.zeros(4)

for i in range(3):
   backup = v
   v[0] = 1
   print(backup)

My output is:

[1. 0. 0. 0.]
[1. 0. 0. 0.]
[1. 0. 0. 0.]

But I expected:

[0. 0. 0. 0.]
[1. 0. 0. 0.]
[1. 0. 0. 0.]

Why does backup matrix get updated before assignment?

martineau
  • 119,623
  • 25
  • 170
  • 301
TNT2631
  • 61
  • 1
  • 6
  • Also, for reference: [Numpy array assignment with copy](https://stackoverflow.com/q/19676538/3005167) – MB-F Feb 01 '19 at 07:53

2 Answers2

5

You are not really doing back up: you are just making another reference.

Making a copy solves it:

import numpy as np
v = np.zeros(4)
backup = np.zeros(4)

for i in range(3):
    backup = v.copy()
    v[0] = 1
    print(backup)

[0. 0. 0. 0.]
[1. 0. 0. 0.]
[1. 0. 0. 0.]
Chris
  • 29,127
  • 3
  • 28
  • 51
1

I think backup = v is not making a copy its is just assigning the values.

Ananya Pandey
  • 157
  • 1
  • 1
  • 9