We have a class of TippyState having TippyState.current_grid containing a list of list representing the current grid of the game state.
In the method TippyState.apply_move(move), we first have
new_grid = self.current_grid
(then we modified the new_grid to the grid of the game state after the move is applied)
return TippyState(new_grid)
The problem happened when we modified the new_grid, because our modification changed the self.current_grid as well.
Then we tried:
new_grid = self.current_grid.copy()
(then we modified the new_grid to the grid of the game state after the move is applied)
return TippyState(new_grid)
We thought it would work because we used list.copy() instead of just assigned the value of self.current_grid to new_grid, so we thought the modification of new_grid should not affect the self.current_grid.
However, this is still WRONG!!! Both self.current_grid and new_grid are list of list, which means, although the outer lists have different ids, the inner list still share the same ids. When we are changing the content of the inner list, both self.current_grid and new_grid are changed.
conclusion of the problem:
L = [1, 2, 3, 4]
L1 = L
L1[0] = 0
L1
[0, 2, 3, 4]
L
[0, 2, 3, 4]
L = [1, 2, 3, 4]
L1 = L.copy() 【or L1 = L[:]】
L1[0] = 0
L1
[0, 2, 3, 4]
L
[1, 2, 3, 4]
L = [[1, 2], [3, 4]] L: id1 id1(list):[id2 ,id3] id2(list):[id4, id5] id3(list):[id6, id7]
L1 = L.copy() L1:id8 id8(list):[id2, id3]
L1[0][0] = 0 id2(list): [id9, id5] 【so both L and L1 are changed】
L1
[[0, 2], [3, 4]]
L
[[0, 2], [3, 4]]
At the end, we used a for loop to append every list.copy() of self.current_grid on to new_grid, only in this way, we can make the inner list of current_grid and new_grid have different ids.
So yeah, we should be very careful dealing with lists, especially with copy of lists! of lists! of lists!