Concept of implicit variables?


#1

I don't really have an exercise that I'm stuck at, but I do have a concept that I can't seem to understand. For example (taking an example from the exercise):


board = []

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

print (board)


There is no instance of "i" anywhere else except right before the range. Why isn't there a syntax error (Something like NameError: name 'i' is not defined)? How does "i" just implied to be a variable that is a placeholder?

Thank you in advance!

Best,
John


#2

But it is defined so no exception is raised. In this instance i acts as an internal counter, even though it is not referenced in the loop. It is a perfectly valid way to iterate over a set range.


#3

Hmm... I guess its kinda difficult to wrap my head around it.

Usually I can tell that my code makes sense when I look at it as a sentence. But if someone were to tell me a sentence such as:

"For anything in range of 0 to 5, write this thing I gave you", I wouldn't understand the directions.

How does the computer implicitly know that the variable 'anything' is a direction to count from 0 all the way to 5?

I guess to summarize my question, how does the computer know that the variable that I just randomly assigned is an internal counter?

(Thank you so much for your quick response!)


#4

It uses the variable defined in the for statement and automatically accumulates it on each iteration. A for statement is an iterator (see, __iter__(), __next__() and StopIteration).


#5

You're telling it what values to produce by providing an iterable. Here, you're using the range function to create a list of values, the loop will step through that list and assign each value to the variable name that you specified (i)
So i isn't a counter of any kind, it is one of the values that range produced


#6

I think I get it now. Thank you guys both! :slight_smile: