python - List index changes multiple elements -


I did not match my problem, so hopefully it was mentioned somewhere earlier and I I'm also stupid to find it.

  thelist = [] a = [0] in the category (5): thelist.append (a) print (list)   

at this point , Program [0], [0], [0], [0], [0]]

  lists [0] .append (1) Print (list)   

After adding it I hope that it will return it, but with the first element modified, like:

  [[0, 1], [0] ], [0], [0], [0]]   

What really is, is that every element was modified in the same way and I get the following. / P>

  [[0, 1], [0, 1], [0, 1], [0, 1], [0, 1]]   

I have come to know that if I replace a line 2 with the value of 2, then everything works fine but when I add a variable several times why do not I do this work?

When creating a list, this is the saving of the context of the same object in each state (A) when you first Element, then it actually engages in all the "list" slots What you need to do is create a deep copy on the object during construction:

  thelist = [] a = [ 0] for the category (5): thelist.append (list (A)) print (list)   

Then the following attachment will work as desired.

Comments

Popular posts from this blog

c - Mpirun hangs when mpi send and recieve is put in a loop -

python - Apply coupon to a customer's subscription based on non-stripe related actions on the site -

java - Unable to get JDBC connection in Spring application to MySQL -