0
def move(board, dir):
    tempt = []
    tempt = board[:]
    #print(tempt)
    if dir == 'down':
        for a in range(Grids):
            for b in range(Grids-1, -1, -1):
                if board[a][b] != 0:
                    check = CheckBlock(a, b, dir)
                    board[a][b].moving(board, dir, check[1], check[0])
                    #print(tempt)                   
    if dir == 'up':
        for a in range(Grids):
            for b in range(Grids):
                if board[a][b] != 0:
                    check = CheckBlock(a, b, dir)
                    board[a][b].moving(board, dir, check[1], check[0])
    if dir == 'left':
        for a in range(Grids):
            for b in range(Grids):
                if board[b][a] != 0:
                    check = CheckBlock(b, a, dir)
                    board[b][a].moving(board, dir, check[1], check[0])
    if dir == 'right':
        for a in range(Grids):
            for b in range(Grids-1, -1, -1):
                if board[b][a] != 0:
                    check = CheckBlock(b, a, dir)
                    board[b][a].moving(board, dir, check[1], check[0])

I was recreating some games when I stumbled upon this mess. So this is a function to move everything inside a list while changing the list itself (which is board). And at the end, I want to make sure that something changed in the list. So I made a temporary list (which is tempt) and copied the base list to compare later. But when the base list is modified, the temporary list is modified as well. So the two #print(tempt) code will print out the different list.

I have tried my best to indicate the problem, by calling the function only once, but somehow the temporary list keeps changing whenever I make any modifications to the base lists.

Thank you very much for reading through here, any bits of help or thoughts are appreciated.

  • Do you know what a shallow copy is? If not, please have a look at [this QA](https://stackoverflow.com/questions/184710/what-is-the-difference-between-a-deep-copy-and-a-shallow-copy) – Pynchia Sep 18 '19 at 06:16

1 Answers1

0

To Simulate the problem, What you are doing right now is as follows:

>>> a=[[1,2,3,4]]
>>> a
[[1, 2, 3, 4]]
>>> b=a[:]
>>> b
[[1, 2, 3, 4]]
>>> a[0].append(5);
>>> a
[[1, 2, 3, 4, 5]]
>>> b
[[1, 2, 3, 4, 5]]
>>> a.append(6)
>>> a
[[1, 2, 3, 4, 5], 6]
>>> b
[[1, 2, 3, 4, 5]]

You are thinking that by just doing b=a[:] all the references will be removed, But its now how it works It still is a shallow copy. To avoid this behavior You have to use deep copy as below:

>>> import copy
>>> a=[[1,2,3]]
>>> b=copy.deepcopy(a);
>>> a
[[1, 2, 3]]
>>> b
[[1, 2, 3]]
>>> a[0].append(4);
>>> a
[[1, 2, 3, 4]]
>>> b
[[1, 2, 3]]

So In your code replace tempt = board[:] with tempt = copy.deepcopy(board)