0

I have a list currentCell which contains info like coordinates and values and stuff. I then create a copy of that list using currentCellNew = currentCell.copy(). Im told that doing that and modifying the copy will NOT effect the original. But when i remove something from the copy, it also removes it from the original list.

Here is the code that removes from the copy:

#some variables exist outside of scope
        currentCell       = next(x for x in self.cells if x[0] == currentCellCoords)
        currentCellNew    = currentCell.copy()
        if currentCellNew[3] == 0:
            if **condition**:
                wallAxis = next(x[0] for x in list(self.Orientations.items()) if x[1] == "f")

#### Here is the code that removes the element from the copy #####
                currentCellNew[2].remove(next(x for x in currentCellNew[2] if x[0] == wallAxis))
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61

1 Answers1

1

list.copy() is a shallow copy; it's fine when the original list contains immutable objects, but it looks like you've got a list of lists, and those inner lists aren't being copied (the new outer list has references to the same inner lists as the first one).

You need to use the copy.deepcopy function to perform the original copy, thereby copying the contents, not just the top-level references:

import copy   # At top of file

...
currentCellNew    = copy.deepcopy(currentCell)
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271