1

I am trying to create a simple board in a draw_board definition that will use size and several coordinates where I will place 1 character length characters in specified coordinates. I am in the beginning stages and want to just simply create the board itself using a 2d array.

This method below works when I change individual elements :

board = [['','','',''], ['','','',''], ['', '', '', ''], ['','','','']]
board[0][0] = 'a'

print('   0  1  2  3')
print('0  ' + board[0][0] + '  ' + board[0][1] + '  ' + board[0][2] + '  ' + board[0][3])
print('1  ' + board[1][0] + '  ' + board[1][1] + '  ' + board[1][2] + '  ' + board[1][3])
print('2  ' + board[2][0] + '  ' + board[2][1] + '  ' + board[2][2] + '  ' + board[2][3])
print('3  ' + board[3][0] + '  ' + board[3][1] + '  ' + board[3][2] + '  ' + board[3][3])

However, I would not be able to change the size by just a variable and would need to edit the initialization of the board myself.

This method below is better and would work because I could easily change the size variable and get any size board I want...

size = 4
board = [['']*size]*size
board[0][0] = 'a'

print('   0  1  2  3')
print('0  ' + board[0][0] + '  ' + board[0][1] + '  ' + board[0][2] + '  ' + board[0][3])
print('1  ' + board[1][0] + '  ' + board[1][1] + '  ' + board[1][2] + '  ' + board[1][3])
print('2  ' + board[2][0] + '  ' + board[2][1] + '  ' + board[2][2] + '  ' + board[2][3])
print('3  ' + board[3][0] + '  ' + board[3][1] + '  ' + board[3][2] + '  ' + board[3][3])

However, when I implement board[0][0] = 'a', it changes the entire column to 'a', which is not what I want. Any suggestions of how I could change this second method to make it work for just the desired coordinate?

1 Answer 1

2

Use

board = [['' for i in range(size)] for j in range(size)]

this is because when you use the * operator, you're creating more references to the same object, not more copies.

Here's more in depth information about the strategy used above, called list comprehensions

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.