0

I am new to python, and I am trying to create a 2d list of list array. Below is two approach that I think should work, but one of them is actually not correct.

board = [["."] * n for _ in range(n)]
sth = [["." for _ in range(n)]] * n  

when I perform assigned on [0][0] to replace '.' with 'Q' , sth initialize every row, while board only initialize first row. If list * n is a soft copy, and every list in each row of sth in the same, why would ["."] * n not a soft copy ?

Here's the result before & after assignment.

board[0][0] = 'Q', sth[0][0] = 'Q'

board initialize: [['.', '.', '.', '.'], ['.', '.', '.', '.'], ['.', '.', '.', '.'], ['.', '.', '.', '.']]
board assigned  : [['Q', '.', '.', '.'], ['.', '.', '.', '.'], ['.', '.', '.', '.'], ['.', '.', '.', '.']]
sth initialize  : [['.', '.', '.', '.'], ['.', '.', '.', '.'], ['.', '.', '.', '.'], ['.', '.', '.', '.']]
sth assigned    : [['Q', '.', '.', '.'], ['Q', '.', '.', '.'], ['Q', '.', '.', '.'], ['Q', '.', '.', '.']]
user2386301
  • 390
  • 1
  • 4
  • 17

0 Answers0