The misconception is that these two loops are not similar.
Java's form is starting from some initial value, printing it out, and so long as the value is less than some terminal value, it will continue the loop.
Python is actually taking each element contained in whatever iterable you give it, and printing out the contents of it without any incrementation whatsoever.
Since in this case, the iterable is the result of range
, the behavior of how you get the elements changes between versions.
If you're using Python < 3, range
is a function that eagerly generates a list of elements for you to use. The lazy, generated variant of this is xrange
, in which the values are generated as needed. In this scenario, since you're looping to completion over the entire collection, and the memory constraints aren't that high, you won't notice any difference between the two.
In Python >= 3, range
behaves similar to xrange
in that it's another sequence type, which also generates the values that it requires on the fly.
The key difference here is that the variable in a Python loop represents the actual value contained in the iterable, whereas Java is generating the value with a standard for
loop.
If you were to use an enhanced-for loop instead, then you'd get closer to how Python's loops work:
int[] list = {1, 2, 3, 4, 5, 6, 7, 8, 9}
for(int i : list) {
System.out.println(i);
}