I feel like this is a very obvious fix that I’m missing and a small snippet taken from my main programme.
emptyBoard = [['N', 'N', 'N'], ['N', 'N', 'N'], ['N', 'N', 'N']]
for i in range(3):
otherBoard = emptyBoard
otherBoard[1][i] = 'Y'
print(otherBoard)
When run the programme outputs the following :
[['N', 'N', 'N'], ['Y', 'N', 'N'], ['N', 'N', 'N']]
[['N', 'N', 'N'], ['Y', 'Y', 'N'], ['N', 'N', 'N']]
[['N', 'N', 'N'], ['Y', 'Y', 'Y'], ['N', 'N', 'N']]
But my desired output would be:
[['N', 'N', 'N'], ['Y', 'N', 'N'], ['N', 'N', 'N']]
[['N', 'N', 'N'], ['N', 'Y', 'N'], ['N', 'N', 'N']]
[['N', 'N', 'N'], ['N', 'N', 'Y'], ['N', 'N', 'N']]
My intention is to reset otherBoard to emptyBoard with every new iteration , but that doesn’t seem to be happening?
Thanks
>Solution :
otherBoard = emptyBoard makes both variables point at the same list. Since both variables are pointing at the same object, changing that object will reflect through both variables.
The easiest way to do what you actually want should be this:
import copy
emptyBoard = [['N', 'N', 'N'], ['N', 'N', 'N'], ['N', 'N', 'N']]
for i in range(3):
otherBoard = copy.deepcopy(emptyBoard)
otherBoard[1][i] = 'Y'
print(otherBoard)
copy.deepcopy() will create a different but identical copy of the given list and its sublists. Then, you assign otherBoard to point to that new, completely separate, copied list, and any changes you make will not reflect on the old list.
A quicker but possibly more error-prone solution, which doesn’t require any extra imports, would be
emptyBoard = [['N', 'N', 'N'], ['N', 'N', 'N'], ['N', 'N', 'N']]
for i in range(3):
otherBoard = emptyBoard
oldValue = otherBoard[1][i]
otherBoard[1][i] = 'Y'
print(otherBoard)
otherBoard[1][i] = oldValue
simply changing the list and then changing it back immediately afterwards.