I am having trouble understanding a Python for loop. For example, here is some code I've made while I'm learning:
board = []
for i in range (0,5):
board.append(["O"] * 5)
Don't worry about what the code does, I just don't understand what the "i" variable means.
In c/java the for loop wiil be:
here for every iteration i will be incrementing +1 value till i reaches 10, after that it comes out of loop. In same way,in python the for loop looks like:
here i performs same operation and i is just a variable to increment a value.
In short,
i
refers to the current element in the list.Your list is defined as: 0, 1, 2, 3, 4 and 5. Therefore
i
will iterate this list and assign itself to the next item,i
is 0, next iterationi
will be 1, next iterationi
will be 2 etc.Directly from python.org:
The for statement in Python differs a bit from what you may be used to in C or Pascal. Rather than always iterating over an arithmetic progression of numbers (like in Pascal), or giving the user the ability to define both the iteration step and halting condition (as C), Python’s for statement iterates over the items of any sequence (a list or a string), in the order that they appear in the sequence. For example (no pun intended)
Results in:
http://docs.python.org/2/tutorial/controlflow.html
It's an unused variable. Python syntax requires a variable in that position, but you don't do anything with it since you simply want to repeat an action 5 times.
Some people prefer the convention of naming an unused variable like this
_
:but this name can interfere with
gettext
.The for loop iterates over the given list of objects which is
[0, 1, 2, 3, 4]
obtained fromrange(0,5)
and in every iteration, you need a variable to get the iterated value. That is the usei
here. You can replace it with any variable to get the value.Another example:
But in the code you have given, the variable
i
is not used. It is being used. just to iterate over the list of objects.Think of it as substitution.
range(0,5)
is[0,1,2,3,4]
. The for-loop goes through each element in the list, naming the elementi
.Prints 0,1,2,3,4.
In your example, i is a placeholder. It is used simply just to loop something x amount of times (in this case, five as the length of range(0,5) is 5)
Also, have fun learning python at Codecademy (I recognise the task :p)
It's an iterator, you can see it as a bucket that stores the result of each iteration; the thing that adds confusion is the fact that it's simply unused in your script, this is another script with a "more involved" use of iterators.
as you can see you can name it as you want, it's the syntax that makes that word an iterator.