user3007200
user3007200

Reputation: 25

Weird error when replacing elements in 2d array

in_file = open("3.8.2.txt",'r')


height = 8
width = 11
board = []
liner = []
for i in range(200):
    liner.append("0")
for i in range(200):
    board.append(liner)

for i in range(height):
    line = in_file.readline().strip("\n").lower()
    for j in range(len(line)):
        board[50 + i][50 + j] = line[j]

I am trying to place a 2d board around a bunch of 0's. Instead of getting a nice board in the middle, the last line of the board is placed in the middle of each line on the board. I have no idea why.

Here's the output:

00000000000000000000000000000000000000000000000000yuiqlxcnbjf000000000000000000000000
00000000000000000000000000000000000000000000000000yuiqlxcnbjf000000000000000000000000
00000000000000000000000000000000000000000000000000yuiqlxcnbjf000000000000000000000000
00000000000000000000000000000000000000000000000000yuiqlxcnbjf000000000000000000000000
00000000000000000000000000000000000000000000000000yuiqlxcnbjf000000000000000000000000

My expected output would be something like this:

000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000
00000000000000000letterss00000000000000000000000000000
00000000000000000letterss00000000000000000000000000000
00000000000000000letterss00000000000000000000000000000
00000000000000000letterss00000000000000000000000000000
00000000000000000letterss00000000000000000000000000000
000000000000000000000000000000000000000000000000000000
000000000000000000000000000000000000000000000000000000

Upvotes: 1

Views: 41

Answers (1)

thefourtheye
thefourtheye

Reputation: 239443

The actual problem is in these line

for i in range(200):
    board.append(liner)

You are not creating 200 new lists and appending it to board. Instead, you are adding 200 references to the same list in board. What you should do is, create a copy of the linear and append it to board like this

for i in range(200):
    board.append(liner[:])

The board preparation can be written like this

board = [["0"] * 200 for _ in range(200)]

Upvotes: 3

Related Questions