Why it includes -1


#1

When you ask a question, don’t forget to include a link to the exercise or project you’re dealing with!

If you want to have the best chances of getting a useful answer quickly, make sure you follow our guidelines about how to ask a good question. That way you’ll be helping everyone – helping people to answer your question and helping others who are stuck to find the question and answer! :slight_smile: def random_row(board_in):
a = randint(0,len(board_in) - 1)
return a
i am currently doing an exercise on how to make a battleship game and when having to select a number randomly it tells me to include a negative 1 (-1), why?


#2

The length of the board is 1 more than the highest index. If we generate a randint from 0 to len, it could overflow, so to prevent this, we subtract 1; but, doing so could put us at index -1, so we start randint with 1 instead of zero.

randint(1, len(board) - 1]

If we compare a zero indexed list to the a default range of the same length, they match up perfectly.

s = [3, 6, 9, 12, 15]
r = range(len(s))
print r
# [0, 1, 2, 3, 4]

Notice how the range lines up perfectly with the indices?

Now if we really want to generate a number that cannot overflow, then randrange fits that bill. It will produce a number that is in range, and does not need to be modified to suit.

randrange(len(board))

The output will always match up to a list index.