Create and initialize 5x5 grid for Battleships

grid, initialization, list, python

Solution

["O"]*5

This creates a list of size 5, filled with "O": `["O", "O", "O", "O", "O"]`

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

This appends (adds to the end of the list) the above list to board[]. Doing this 5 times in a loop creates a list filled with 5 of the above lists.

[["O", "O", "O", "O", "O"],
["O", "O", "O", "O", "O"],
["O", "O", "O", "O", "O"],
["O", "O", "O", "O", "O"],
["O", "O", "O", "O", "O"]]

Your code did not work, because lists are not initialized with a size in python, it just starts as an empty container `[]`. To make yours work, you could have done:

board = [[],[],[],[],[]]

and in your loop:

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

Problem

So I just completed a section of CodeAcademy Battleship problem, and have submitted a correct answer but am having trouble understanding why it is correct. The idea is to build a 5x5 grid as a board, filled with "O's". The correct code I used was: ``` board = [] board_size=5 for i in range(board_size): board.append(["O"] *5) ``` However I'm confused as to why this didn't create 25 "O's" in one single row as I never specified to iterate to a separate row. I tried ``` for i in range(board_size): board[i].append(["O"] *5) ``` but this gave me the error: `IndexError: list index out of range`. Can anyone explain why the first one is correct and not the second one?

Original source