-4

Let's take the following code

board = [[0,0,0],[0,0,0],[0,0,0]]
versionsOfBoard = []
versionsOfBoard.append(board); #this will keep the versions of board array
print(versionsOfBoard);
# output
# [[[0,0,0],[0,0,0],[0,0,0]]]
# later I change few values in the board and append 'board' to my versions array
board[0][0] = 1
versionsOfBoard.append(board)
print(versionsOfBoard)
# output
# [[[1, 0, 0], [0, 0, 0], [0, 0, 0]], [[1, 0, 0], [0, 0, 0], [0, 0, 0]]]
# if you notice here, the 0th index value is also changed
board[1][2] = 1
versionsOfBoard.append(board)
print(versionsOfBoard)
# output
# [[[1, 0, 0], [0, 0, 1], [0, 0, 0]], [[1, 0, 0], [0, 0, 1], [0, 0, 0]], [[1, 0, 0], [0, 0, 1], [0, 0, 0]]]

Every index value displays the latest state of 'board'. it is referencing the board. I have tried with .append(board[:]) and .append(board.copy()). Both these options too do not solve the problem.

Any help would be highly appreciated

Abishek
  • 152
  • 1
  • 7

1 Answers1

0

Try this

import copy
board = [[0,0,0],[0,0,0],[0,0,0]]
versionsOfBoard = []
versionsOfBoard.append(copy.deepcopy(board))
print(versionsOfBoard);

board[0][0] = 1
versionsOfBoard.append(copy.deepcopy(board))
print(versionsOfBoard)

board[1][2] = 1
versionsOfBoard.append(copy.deepcopy(board))
print(versionsOfBoard)
deadshot
  • 8,881
  • 4
  • 20
  • 39