Understanding code logic -> 3. Make a list


#1

Hello,

I would like some help trying to understand the logic behind this code:

board = []

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

When we write range(5) this creates a list of four integers from zero to four [0, 1, 2, 3, 4], correct?
So does that mean that the i in the for i in range(5) loop refers to the actual integers?
So in other words we’re saying “hey, for each item/integer in this list do the following… ?” So the integers in this list/range are irrelevant in this specific case, we’re just using them as an instrument of reference to execute something else an X amount of times?

Hope I didn’t make that too confusing lol,

Regards


#2

It actually creates five integers, which are the ones you listed.

Yes, in this case, we are just using i as a counter, so that we can do something 5 times. However, if we wanted to use the values of i during each iteration of the loop, we could do so.


#3

Yeah my bad, that’s what I meant.

Mind showing me a quick example? :grin:

So any time I want to execute some action several times in python the best thing is to use a for loop and a range? (Instead of copy-pasting the action the amount of times we want it. That would be ugly code I’m assuming)


#4

Perhaps, for another game, we want a triangular board instead of a square one …

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

Then each row will have one more "O" than the preceding one, since i increases by 1 during each loop iteration.

In many situations, it is a great way to do it, especially when you need a counter, as in the current exercise. There are additional choices for managing a loop, for example …

name = "Monty"
for char in name:
  print(char)

#5

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