0
Input = 5
GM1 = [0 for x in range(Input)]
GameBoard = [GM1 for x in range(Input)]
print(*GameBoard, sep="\n")
GameBoard[1][1] = 5
print(*GameBoard, sep="\n")

ok so in the final print statement, I expect this result:

[0, 0, 0, 0, 0]
[0, 5, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]
[0, 0, 0, 0, 0]

but instead, I'm getting

[0, 5, 0, 0, 0]
[0, 5, 0, 0, 0]
[0, 5, 0, 0, 0]
[0, 5, 0, 0, 0]
[0, 5, 0, 0, 0]

Why is this happening and how can I solve this?

I think the problem is about list comprehension I used.

3 Answers3

0

Try this:

GameBoard = [GM1.copy() for x in range(Input)]

And this article will help you to understand what's going on: Immutable vs Mutable types

iYasha
  • 61
  • 4
0

The problem is not the list comprehension, but something that is called aliasing. In your case, this means that GameBoard is actually referencing the same object 'GM1' five times.

When you modify one item in a row of GameBoard, you are actually modifying the item at index 1 of the GM1 list, which is shared by all of the rows of GameBoard. Since GM1 is used as the rows of GameBoard, this means that the change is applied to all of the rows of GameBoard.

This issue can be avoided by making a copy of GM1, instead of a direct reference, as iYasha pointed out in their answer:

GameBoard = [GM1.copy() for x in range(Input)]

Each row will then be a separate list, so modifying one item in the list will not affect the other rows (lists).

Robinho
  • 21
  • 2
0

and how can I solve this?

it's quite easy:

GameBoard = [[0]*Input for _ in range(Input)]
SergFSM
  • 1,419
  • 1
  • 4
  • 7