0

It seems like a very silly question, but I stuck on this. Let's say that I have code like this:

board = [[False] * 4] * 4

s = {(0, 3), (1, 3), (2, 1), (3, 0)}

for row in range(4):
    for col in range(4):
        board[row][col] = (row, col) in s
print(board)

I accepted to find that the board get the True values in the tuple places, like this:

[[False, False, False, True], [False, False, False, True], [False, True, False, False], [True, False, False, False]]

But I got :

[[True, False, False, False], [True, False, False, False], [True, False, False, False], [True, False, False, False]]

Why ?????

Yosef Cohen
  • 91
  • 2
  • 8
  • 4
    I'm sure someone will quickly find the duplicate question which will answer all this for you, but in short, you have multiple references to the same sublist. – alani Aug 09 '20 at 18:35
  • 4
    Try something like `board = [[False for x in range(4)] for y in range(4)]` – alani Aug 09 '20 at 18:37
  • 5
    Does this answer your question? [List of lists changes reflected across sublists unexpectedly](https://stackoverflow.com/questions/240178/list-of-lists-changes-reflected-across-sublists-unexpectedly) – ywbaek Aug 09 '20 at 18:38
  • Well found, @ywbaek, thank you. BTW, I think in fact that probably the inner list comprehension was not needed in my above example. But the outer one certainly is. – alani Aug 09 '20 at 18:39
  • Voting to close as duplicate with the link that ywbaek found. [EDIT: seems it's already done.] – alani Aug 09 '20 at 18:40

0 Answers0