3.Make a List


#1


I get this error when trying to print my battleship board:
"Oops, try again. It looks like you do not have 5 rows in your list."
The print looks correct, but I don't know what I'm doing wrong.


#My code:

board = []

for i in range(5):
    print ["O"] * 5
    
board.append(i)

#Which prints

board.append(i)
['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']
None


#2

board = []

for i in range(0,5):
board.append(["O"] * 5)


#3

Hi,

what you're doing wrong is :
- you're printing it right (the print ["O"] * 5 does all the job)
- but the only thing you add to board is the last i value ( i = 4 in the last loop).
If you print board, you'll see there is something wrong.

The append method needs to be inside the for loop.

you have several options to resolve it :

board = []
for i in range(5) : 
     board.append(['O','O','O','O','O'])
print board

# or
board = []
for i in range(5) : 
     board.append(['O']*5)
print board

# or 
board = []
for i in range(5):
   board.append([])
   for j in range(5):
       board[i].append('O')
print board

#4

Just what I was looking for, thanks a million:)


#5

do you have any insight as to why this method would return the same error as the op?

def create_board(x):
board=[]
for i in range(x):
board.append(["O"]*x)
return board

print create_board(5)


#6

@benvaughann : I'm glad it helped :slight_smile:

@a_elise : you're function definition is perfect, that's why you have the output you wanted. However I think the system in Codecademy will check what's inside the board variable : yours doesn't exist (you use it in the function declaration, but you don't store it with the values you want).

Then you have several options :

  • store the output in a variable called board :

def create_board(x):
	board = []
	for i in range(x):
		board.append(["O"]*x)
	return board

board = create_board(5)
print board

The board outside the function declaration is a global variable, and the board inside the function definition is a local variable (works only for this function). They don't have to get the same names, it will make no difference. Example :

def create_board(x):
	whatsthefuck = []
	for i in range(x):
		whatsthefuck.append(["O"]*x)
	return whatsthefuck

board = create_board(5)
print board
  • you can also take the global variable as a parameter :

board = []

def create_board(x, board):	
	for i in range(x):
		board.append(["O"]*x)
	return board


print create_board(5, board)   # print board

#7

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