Python Code Question - For Loop


I do not understand the below code used in step 4-6 (and maybe after).

for i in range(5):
board.append([“O”] * 5)

Would someone please be able to explain what this is used for?



A for loop is a way of saying “This many times, do this action”
So the first line becomes “execute the following code, five times”

The next line tells the board object to add [“O”] five times
That line will be repeated as many times as the for loop dictated

#setting up a board so our following code has somewhere to append to
board = []

for x in range(5):
  #execute this code
  board.append(["O"]) # not including * 5 for demonstration
print board



x is first equal to 0 then 1 then 2 then 3 then 4
range(5) excludes 5. We start the count from zero, so there are still 5 digits to go through.

When x is 0 we append a [“O”] to the board. So board = [[‘O’]]
When x is 1 we append another [“O”] to the board. board = [[‘O’],[‘O’]]
The function appends [“O”] until x == 4. when x == 4 then the board = [[‘O’],[‘O’],[‘O’],[‘O’],[‘O’]]


I am a little confused with the second example. If range(5) prints 0,1,2,3,4 then why would range(1) print 0,1?

I think this is probably something simple I am just overlooking but please let me know.



Not your fault you were confused by the second example. I told you wrong :/. I removed the second example cause it was wrong.

print range(1) would only print [0]
print range(0,1) also prints [0]

range(num) excludes num
However range(num1,num2) num1 is included and num2 is still excluded
You can think of num1 as the number you start counting at. if range() only had one parameter then that is the number you stop counting before.

Therefore print print range(1,3) prints [1,2] because we specified to start at 1 and go up to the number before 3

You can also have a third parameter in range() that specifies the increment or step you count by.
print range(0,5,2) prints [0,2,4]

I recommend messing around with range() until you get a solid understanding.


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