-4

I am trying to copy a vector several times and then change one of its elements:

from copy import deepcopy

v = [0.5,1.0,2.0]
m = 3 * [deepcopy(v)]
# m = [[0.5,1.0,2.0],[0.5,1.0,2.0],[0.5,1.0,2.0]]
m [0][0] = "Python"
# m = [["Python",1.0,2.0],["Python",1.0,2.0],["Python",1.0,2.0]]

as you can see instead of just changing the 0 element form the 0 array, it is changing all the 0 elements. What am I doing wrong?

Thanks!

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Mariano
  • 295
  • 1
  • 4
  • 13

1 Answers1

4

What you did here was that you made three references to the same thing.

3 * [deepcopy(v)] simply made 3 different references to the same list.

You would want to do

m = [deepcopy(v) for x in range(3)]
Kenta Nomoto
  • 839
  • 6
  • 11