13/19 IndexError: list index out of range"


#1
from random import randint

board = []

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

def print_board(board):
    for row in board:
        print " ".join(row)

print_board(board)

def random_row(board):
    return randint(0, len(board) - 1)

def random_col(board):
    return randint(0, len(board[0]) - 1)

ship_row = random_row(board)
ship_col = random_col(board)
guess_row = int(raw_input("Guess Row:"))
guess_col = int(raw_input("Guess Col:"))

print ship_row
print ship_col

Write your code below!

if guess_row == ship_row and guess_col == ship_col:
    print "Congratulations! You sank my battleship!"

else:
    if guess_row not in range(6) or guess_col not in range(6):
        print "Oops, that's not even in the ocean."

    elif board[guess_row][guess_col] == "X": <--- line 36 (referenced in error)
        print "You guessed that one already."

    else:
        print "You missed my battleship!"
        board[guess_row][guess_col] == "X"
    print_board(board)

I've seen a few other people with this error or similar ones:

Traceback (most recent call last):
File "python", line 36, in
IndexError: list index out of range

But the answers to those usually say to add "board" in front of [guess_row][guess_col], I do have that written though so I can't figure out what's wrong.


#2

I think your code for the second elif is correct, I'm using the exact same code in my testing without error. I think your issue is in the first else:if; which I'd recommend rewriting as an elif.

In that line, you're using a fixed range of 6, which isn't right:

else:
if guess_row not in range(6) or guess_col not in range(6):
print "Oops, that's not even in the ocean."

The grid is 5x5, but the addresses for the grid are 0 through 4. Your code fails with the error you'd noted if you test a row or column value of 5. You could try using a bit different approach to that section like this:

elif guess_row not in range(0,len(board)) or \
guess_col not in range(0,len(board[0])):
print "Oops, that's not even in the ocean."

This also has the benefit of using the actual board width for validation. So, if you change the board width or length this code will adapt.

Does change change address your error?


#3

Yeah that was it, I changed that earlier cause I was having some other error and forgot to switch it back when I fixed it. Thanks for the help. :smile: