Home > database >  Variable not assigning correctly inside a for loop
Variable not assigning correctly inside a for loop

Time:10-08

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

CodePudding user response:

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.

CodePudding user response:

You can use the following code to do the task. Actually, otherBoard = emptyBoard doesn't make a second list. Both the otherBoard and emptyBoard refer to the same list after the assignment because the assignment just replicates the reference to the list.

emptyBoard = [['N', 'N', 'N'], ['N', 'N', 'N'], ['N', 'N', 'N']]
for i in range(3):
    otherBoard = emptyBoard.copy()
    secondbord = otherBoard[1].copy()
    secondbord[i] = 'Y'
    otherBoard[1] = secondbord
    print(otherBoard)
  • Related