Make a List - Battle Ship


#1

How do you make a 5 x 5 board into a list? I could only write a list of 5 zeros, put it into a list and print it 5 times.

My Code:

board = []
list = ["O"] * 5
board.append(list)

for i in range(0, 5):
print board


#2

You just have to append created list five times:

board = []
list = ["O"] * 5

for i in range(0, 5):
    board.append(list)

print board

You can also use the same method as before:

board = [["O"] * 5] * 5

print board

#3

Thank you for your answer but I keep getting the error:

Oops, try again. It looks like your board has 5 references to the same row! This will cause problems later on. Read the hint for more information and use a for loop to complete this lesson

I have no idea how to fix it.


#4

Let's start with what's wrong with the previous solution. Let's say that you want to change value of one cell:

board = []
list = ["O"] * 5

for i in range(0, 5):
    board.append(list)

board[0][0] = 'X'

print board

And the result is:

[
['X', 'O', 'O', 'O', 'O'],
['X', 'O', 'O', 'O', 'O'],
['X', 'O', 'O', 'O', 'O'],
['X', 'O', 'O', 'O', 'O'],
['X', 'O', 'O', 'O', 'O']
]

Do you know why this happened?


To fix this we can use this code:

board = []
for x in range(5):
    board.append(["O"] * 5)

print board

#5

Thank you.

I am guessing the statement

board [0] [0] = 'X'

Is the indexing form of a list containing other similar lists.

Could you please explain that statement with the double [0]. Thank you.