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?
["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
Python lists start out empty:
board = [] # empty list
Unlike some programming languages, you do not specify or initialise the bounds of the array, so if you try to access by index:
board[0]
you will get an IndexError
; there is not yet any index 0
.
In the first version, on each trip through the for
loop, you append
(add to the end of the list) a new list containing five "O"
s. If you want the board
list to contain 25 "O"
s, you should use extend
instead:
for i in range(board_size):
board.extend(["O"] *5)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With