0

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

  • Does this answer your question? [How to make a copy of a 2D array in Python?](https://stackoverflow.com/questions/6532881/how-to-make-a-copy-of-a-2d-array-in-python) – kcsquared Sep 25 '21 at 01:01
  • You don't need to us copy.deepcopy (although saying "I can't use libraries" is really a nonsensical restriction for the standard lib, but ok whatever). Just **implement a deep copy for your nestes list**. It's trivial – juanpa.arrivillaga Sep 25 '21 at 01:06

1 Answers1

1

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)]
U13-Forward
  • 69,221
  • 14
  • 89
  • 114