0

So I was trying to solve the N queens problem in Python, and I generated my chess board using the following statement, in my Solution class:

self.board = [[0] * self.dimension] * self.dimension

where dimension is initialized to the value that defines the number of Queens, and hence the size of the chessboard

After obtaining a list of possible positions ( a list of tuples, held in the class variable queen_positions, where each tuple holds a position on the board), I attempted to print the solution using the following:

    def print_board(self):
    """
    Prints the board
    """
    for i, j in self.queen_positions:
        self.board[i][j] = 'Q'
    print(self.board)

And much to my horror, instead of updating the specific coordinates specified by the indices, it also updated additional coordinates. For instance, for position (0,1), after the update, my board looked like this:

[[0, 'Q', 0, 0], [0, 'Q', 0, 0], [0, 'Q', 0, 0], [0, 'Q', 0, 0]]

I noticed that if I did not generate the board at the beginning, but hard coded it as a 4x4 list, this does not happen.

From IDLE

board = [[0,0,0,0],[1,1,1,1], [2,2,2,2], [3,3,3,3]]
for i,j in [(1,1),(2,2)]:
    print(f"i is ${i} and j is ${j}")
    board[i][j] = 'Q'
>>> board
[[0, 0, 0, 0], [1, 'Q', 1, 1], [2, 2, 'Q', 2], [3, 3, 3, 3]]

What am I missing here?

  • Because `[[0] * self.dimension] * self.dimension` first creates a list, `[0] * self.dimension`. Then it creates *another* list with `self.dimension` references to that first list. – juanpa.arrivillaga Mar 10 '21 at 17:44
  • Ah...so what would be the workaround for this? Should I copy self.board to another variable? Or is there a better way I can initialize a multi dimensional list in a Pythonic fashion? – Prashanth Raghavan Mar 10 '21 at 19:06
  • Look at the linked duplicate, but `[[0] * self.dimestion for _ in range(self.dimension)]` would work here – juanpa.arrivillaga Mar 10 '21 at 19:09

0 Answers0