0

I'm trying to get a nested for loop to build a chessboard, in which the the chessboard is a list, with a list for each row, each of which contains a list that contains eight lists of length 2 to reference which diagonals that particular square lies on.

board = [[[0]*2]*8]*8

Generates the following:

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

Which is what I want, but then the following code:

for i in range(8):
    for j in range(8):
            #left diagonals, Upper left corner is 0th row, Right diagnonals, upper right corner is 0th row [l,r]
            board[i][j][:] = [i + j, 7 - i + j]

Generates:

[[[7, 0], [8, 1], [9, 2], [10, 3], [11, 4], [12, 5], [13, 6], [14, 7]],
 [[7, 0], [8, 1], [9, 2], [10, 3], [11, 4], [12, 5], [13, 6], [14, 7]],
 [[7, 0], [8, 1], [9, 2], [10, 3], [11, 4], [12, 5], [13, 6], [14, 7]],
 [[7, 0], [8, 1], [9, 2], [10, 3], [11, 4], [12, 5], [13, 6], [14, 7]],
 [[7, 0], [8, 1], [9, 2], [10, 3], [11, 4], [12, 5], [13, 6], [14, 7]],
 [[7, 0], [8, 1], [9, 2], [10, 3], [11, 4], [12, 5], [13, 6], [14, 7]],
 [[7, 0], [8, 1], [9, 2], [10, 3], [11, 4], [12, 5], [13, 6], [14, 7]],
 [[7, 0], [8, 1], [9, 2], [10, 3], [11, 4], [12, 5], [13, 6], [14, 7]]]

Which is incorrect, each of these 2-element lists should have a distinct pair of values in them.

  • 1
    `[[[0]*2]*8` creates a list containing 8 references to the same list. And then adding another `*8` again does the same thing *again*. – juanpa.arrivillaga Nov 12 '17 at 21:21
  • So in general, if you do something like `[x]*3` you'll get `[x, x, x]` where *x* always references the same object. A quick fix for you: `board = [[[0]*2 for _ in range(8)] for _ in range(8)]` – juanpa.arrivillaga Nov 12 '17 at 21:25

0 Answers0