Variable not assigning correctly inside a for loop

Question:

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

Asked By: Freddie Moore

||

Answers:

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.

Answered By: Green Cloak Guy

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)
Answered By: Gihan Chathuranga
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.