Battleship - Make a List - General Question about Loop


#1

I have a general question.

In the code below:

board = []
for i in range(5):
board.append([‘O’] * 5)

How can you loop through “range” when no where in the function is range defined? From my understanding, the for loop is used to loop through a string, list etc. but with range not being defined, how does this work?

Thanks!


#2

Hi @joshuasimi,

range is a Python built-in function, so the programmer does not need to define it. See Python: range.


#3

Got it! Thanks.

And why does this create a 2-dimensional list vs. 1 long list segmented by the inner list?

Is it because the list looks like:

0,
1,
2,
etc.
etc.


#4

This header specifies a loop that iterates 5 times …

for i in range(5):

During each of the 5 iterations, the following line appends a list of 5 elements to the list that represents the board

    board.append([‘O’] * 5)

As a result, board refers to a list of 5 lists, which we can think of as a 2-dimensional list.


#5

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