I was struggling with this bug and couldn't find documentation that explained it.
My code creates a class that uses a list as an instance variable. Simple version of code:
class Board:
def __init__(self):
self.grid = [] #so new instance of grid for each object
When I create two objects and exchange one's grid with a new copy of the other's grid and then run a class method on it, the changes to both grid are synced.
Code:
x = Board()
x.getNewBoard() #creates list with random ints
y = Board()
y.grid = x.grid[:] #new copy, not reference
print(y.grid) #matches x.grid
boardSim(x) #changes to x.grid happen here
print(y.grid) #here the results of y.grid and x.grid are
print(x.grid) #the same despite only running boardSim on x
I tried running it again but this time appending 29834739 to y.grid right after assigning it a copy of x.grid. It did the same syncing, but at the end it had 29834739. x.grid did not have 29834739. When I appended it to x.grid, it synced again but x.grid had the funky number and y.grid didn't.
Then I tried creating a completely different list for y.grid:
x = Board()
x.getNewBoard()
y = Board()
y.getNewBoard()
print(y.grid)
boardSim(x)
print(y.grid)
Grids were not synced: when I ran boardSim(x) it didn't run boardSim(y).
So I thought that maybe I was creating a reference to x.grid instead of a brand new copy, but someone told me that splicing a list creates a copy? I'm using python 3.
Thanks.