Home > database >  Appending python list using the same variable cause new changes to variable be registered in all lis
Appending python list using the same variable cause new changes to variable be registered in all lis

Time:09-25

I summarised the code in my original program for readability and to isolate the main issue. For some reason, when I append the "boom" variable with "poss" (or even poss.copy()), and then make subsequent changes to "poss", the subsequent changes are somehow registered in the original list ("boom"). I do not want this, I want the boom to be a record-keeping variable of sorts that keeps each state of poss. I also can not import libraries (so I can not use solutions like deepcopy() from the copy library).

poss= [
['*', 'j', '*', '*', '*'],
['*', '*', '*', '*', '*']
]
boom = [poss]
#first change
poss[0][1],poss[1][3] = poss[1][3] , poss[0][1]
#first print works well shows correct change
print("First Generation:")
for boomite in boom:
  print(boomite)
  print("\n")
poss[1][3],poss[0][0] = poss[0][0] , poss[1][3]
boom.append(poss.copy())
#This should print two different values but it prints same
print("First and Second Generation:")
for boomite in boom:
  print(boomite)
  print("\n")

#Somehow the second and any successive changes are present in 
#the previous generations 

I get the output: https://i.stack.imgur.com/cPpXL.png

CodePudding user response:

You aren't making a copy of poss in the boom assignment, even poss.copy() wouldn't work, because the list is nested, so you can't shallow copy it, you need to deep copy it.

Instead of:

boom = [poss]

Try:

boom = [[x[:] for x in poss]]

Or with copy.deepcopy:

import copy
boom = [copy.deepcopy(poss)]
  • Related