Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Variable not assigning correctly inside a for loop

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[['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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading