Python for Java Programmers
Chapter 6: Control flow
range
If you would like to simulate a traditional “counter” style Java for loop, you can iterate over a range sequence object/type instead. The range object is an iterable that will ‘dynamically’ generate the next counter value at each iteration of the for loop.
for i in range(0, 10):
print(i)
If you run the example above, you will find that range(0, 10) generates a sequence of numbers from 0 to 9.
The first parameter (start) is optional, and defaults to 0. So range(10) is equivalent to range(0, 10)
for i in range(10):
print(i)
There is also an optional third step parameter. A bit like in Java, it controls how much you increment the counter after each step.
for i in range(0, 10, 2):
print(i)
TIP! If you need a list of numbers, then just convert range to a list!
For example, numbers = list(range(0, 10))