0

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.

Mark Rotteveel
  • 100,966
  • 191
  • 140
  • 197
msun
  • 41
  • 9
  • 4
    What do you store in your `grid` values? `[:]` does a shallow copy, not a deep copy, so if it's a list of lists this is the expected behavior - you copy the list of references so you still have the same underlying objects. `copy.deepcopy()` will do a deep copy. – Peter DeGlopper Jul 25 '16 at 16:07
  • Are these lists *nested*? If so, `[:]` creates a *shallow* copy only. – Martijn Pieters Jul 25 '16 at 16:07
  • Oh yeah, I do! So a shallow copy is a copy of the outside list and the deep copy is a copy of everything? Thanks, I must've spent a good two hours on this. – msun Jul 25 '16 at 16:09
  • @msun: if it is any consolation, I have seen a book which says `[:]` does a deep copy. (I didn't buy it) – cdarke Jul 25 '16 at 16:11
  • @cdarke haha, thanks. :) That mistake, though, is awful – msun Jul 25 '16 at 16:13

0 Answers0