0

I know there are many similar questions like this but I am not sure why my code doesn't work. Basically, what I am trying to do is to initialize a 2D array to all 0s, get user input (row, column), and set the position to 1.

def printBoard(positions):
    for row in positions:
        print(row)

def main()
    x= int(input())
    column = [0] * x
    Board= [column] * x
    printBoard(Board)
    for i in range(x):
        row, column = map(int, input().split())
        Board[row][column] = 1
        printBoard(Board)

main()

But the output is now what I expect.

>>>2 
[0, 0]
[0, 0]
>>>1,1
[0, 1]
[0, 1]

As you can see, the whole column is changed. May I ask why?

DLLM
  • 11
  • 1
  • It is a mess :) for cycle is totally unnecessary. Split the initialization, asking and setting a single field to separate functions. Good luck with your game! – Roman Pavelka Apr 23 '21 at 12:35
  • 2
    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) – Manuel Apr 23 '21 at 12:36

1 Answers1

2

When you execute

Board= [column] * x

it will result in a list in which all rows (i.e. internal lists) will be the same object (x times the list column), so when you update any element of any of those (same) lists, you will see the result x times, since all the rows (or columns as you call it) are exactly the same, because they are the instances of the same object.

quantummind
  • 2,086
  • 1
  • 14
  • 20