Battleship 3 confussed with appending variables


#1

I’m a bit confused as to why I can’t append to my list by defining a variable “row” of 5 O’s and appending that 5 times.

row = ["O", "O", "O", "O", "O"]  #This is a list of five O's which i assign to variable 'row'

def board_gen():
  for i in range(0,5):
    board.append(row) #Here I think i should be appending the above 'row' 5 times.
  return board #Shouldn't this return a list of 5 'row' lists?

Sorry for not putting this in the actual code window thingy, not sure how.


#2

later in the game you want to mark an incorrect guess with an X, if we attempt this in your code:

row = ["O", "O", "O", "O", "O"]  #This is a list of five O's which i assign to variable 'row'

def board_gen():
  for i in range(0,5):
    board.append(row) #Here I think i should be appending the above 'row' 5 times.
  return board #Shouldn't this return a list of 5 'row' lists?

board = board_gen()

board[0][0] = 'X'
print board

we see a bit of a problem, X should only be at a single spot, this is not the case

this is because your code, all the rows refer to the same list in memory.


#3

Okay that makes sense. But shouldn’t it work in making a 5x5 board of O’s anyway? Even if it’s not what we want to do later?


#4

But its a faulty 5x5 board, which gives us problems later down the line, which is why exercise (rightfully) rejects it


#5

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.