0

The following code is part of a larger programme. It has caused a problem, whilst trying to debug it I decided to print the two-dimensional array 'posB' and it keeps changing with every iteration of the loop even though I never seem to change it.

blackBoard = [[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[0,0,0,0,0,0,0,0],[1,1,1,1,1,1,1,1],[5,2,3,4,6,3,2,5]]
possibleMoves = [[6,0,5,0],[6,1,5,1],[6,2,5,2],[6,3,5,3]]
posB = blackBoard
for move in possibleMoves:
    print(posB)
    blackBoard = posB
    blackBoard[move[2]][move[3]] = blackBoard[move[0]][move[1]]
    blackBoard[move[0]][move[1]] = 0

Thank you, please let me know if you could explain what is going on.

nekomatic
  • 5,988
  • 1
  • 20
  • 27
  • Possible duplicate of [How to clone or copy a list?](https://stackoverflow.com/questions/2612802/how-to-clone-or-copy-a-list) – AChampion Feb 01 '19 at 19:33

1 Answers1

0

This happens because list assignments are done by reference in Python. I suggest you to copy the list instead. For example, if you are using Python 3.x(>=3) do as follows:

blackBoard = posB.copy()

You can find more information here: How to clone or copy a list?

Aida
  • 2,174
  • 2
  • 16
  • 33