-1

In this game I'm making, 3's are blocks that people can't move over and 4's are traps. Traps are meant to be hidden but whenever I hide them with the Row variable, it changes the actual Board variable I took the bad code out of my whole program and it looks like this:

Board = [[1, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 0], [3, 0, 0, 0, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 4, 0], [0, 0, 4, 0, 0, 0, 0, 4], [0, 0, 3, 0, 4, 0, 0, 0], [0, 0, 3, 3, 0, 0, 0, 0], [0, 0, 0, 0, 0, 0, 0, 2]]

for Loop in range(len(Board)):
    Row = Board[Loop]
    for Loop2 in range(len(Row)):
        if Row[Loop2] == 4:
            Row[Loop2] = 0
    print(Row)
    print(Board)

Whenever the number 4 is replaced with a 0, it gets replaced with a 0. This is only meant to happen to the variable Row, but also happens to Board for some reason. Any reason why?

Barmar
  • 741,623
  • 53
  • 500
  • 612

1 Answers1

0

Row = Board[Loop]
Row points to the same memory location, that's why changes in it are also copied to Board. Use Row = Board[Loop][:] to create a copy

Abhinav Mathur
  • 7,791
  • 3
  • 10
  • 24