0

I am calling a function making a copy of the list passed in first, making changes to the copied list and then returning it but changes still occur to the original list.

def moveDown(grid):
    tempgrid=grid[:]
    for i in range(3):
        if 0 in tempgrid[i]:
            loc=i
    
    if loc==0:
        return None
    else:
        index=tempgrid[loc].index(0)
        tempgrid[loc][index]=tempgrid[loc-1][index]
        tempgrid[loc-1][index]=0
    return tempgrid
if __name__=="__main__":
    x=[[1,2,3],[4,0,6],[7,5,8]]
    # puzzleSolve(x)
    printGrid(x)
    y=moveDown(x)
    printGrid(x)
    printGrid(y)

this is printed.

******************
   1    2    3 
   4    0    6
   7    5    8
******************
******************
   1    0    3
   4    2    6
   7    5    8
******************
******************
   1    0    3
   4    2    6
   7    5    8
******************
  • 4
    Changes are occuring not to the original list, per se, but to the *lists* that the original list *contains*. This is because `grid[:]` makes a *shallow* copy. You need to keep copying deeper, so `[row[:] for row in grid]` would work – juanpa.arrivillaga Mar 01 '22 at 17:37
  • to copy a list i would expect to see `list.copy()`. Similar to this popular question: https://stackoverflow.com/questions/2612802/list-changes-unexpectedly-after-assignment-why-is-this-and-how-can-i-prevent-it – D.L Mar 01 '22 at 17:46

0 Answers0