Hello all. I apologize in advanced if this has been asked before but I have not been able to find this information via google or searching here. Everything I found is related to how a for loop works. I know how to use a for loop in python and what my input will do and what the output will be. My question is more related to how the syntax itself actually works:

I have the very basic example:

for i in range(10):
    print i

I know that this will print 0 through 9 one at a time and that is the expected output and why it starts at 0 and not 1 and why it ends at 9. My question is more related to how the interpreter knows that "i" is meant for iteration (since I can technically use whatever variable I want) when "i" has no declared value and I never declare i++ or i.next

1 Year
Discussion Span
Last Post by rproffitt

I think you need to step back a second and think that this is not C++. for loops in python are different. They move through what's after the key word "in". So to see what it will iterate through, list that range(10).

Try this one liner in python


Now try that with range(1,11)


Thank you rproffitt. Let me get this straight: "i" is a variable that is based on the reference itself (range(10)). if it were not for range() (or another item) "i" would be meaningless?


I think you're getting it. i gets whatever is in the set of things you after the "in" keyword. It can be numbers, a list of things, and so on. No i++ here.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.