0

I am trying to make two copies of a list, using slicing, called testlist. The two copies are test1,test2. Now I am editing test2 and the values of test1 change. I am not sure why this is happening? I know that slicing creates a new copy of testlist(with a different reference) but somehow test1 and test2 are still related. Any ideas why? Here is the code:

testlist=[[[1,1,1],[1,1,1],[1,1,1]]]
vertices=[]
m=3
for i in range(m):
    for j in range(m):
        vertices.append([i,j])
randv=random.choice(vertices)[:]
test1=testlist[-1][:]
print('test1: ')
print(test1)
test2=testlist[-1][:]
M=[[4,4,4],[4,4,4],[4,4,4]]
uniformv=random.uniform(0,1)
prob=np.exp(beta*M[randv[0]][randv[1]])/(np.exp(beta*M[randv[0]][randv[1]])+np.exp(-beta*M[randv[0]][randv[1]]))
if uniformv<prob:
    test2[randv[0]][randv[1]]=+1
else:
    test2[randv[0]][randv[1]]=-1
print('test1: ')
print(test1)

The print statement for test1 before and after editing test2 yields:

test1: 
[[1, 1, 1], [1, 1, 1], [1, 1, 1]]
test1: 
[[1, 1, 1], [1, 1, -1], [1, 1, 1]]

Please run the code a few times to see different values for test1 because of the usage of random variables.

q2w3e4
  • 195
  • 1
  • 1
  • 7
  • `[:]` only makes a *shallow copy* of a list - the objects contained in the list are also contained in the copy, and modifications to them will be visible via both the original and the copy. `copy.deepcopy()` would be one solution. – jasonharper Jul 26 '22 at 21:45
  • `test1=testlist[-1][:]` and `test2=testlist[-1][:]` each make a separate list object, each of which contains three separate `[1, 1, 1]` lists (which are distinct within `testlist`) - but they each contain **the same sequence of** `[1, 1, 1]` lists. – Karl Knechtel Jul 26 '22 at 21:45

0 Answers0