C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
So: We access the range() immutable sequence. It returns the values 0, 1 and 2, which we print in the loop body.
Iterate: Notice how the program iterates over numbers, but contains no iteration statement like i++. This expression is handled by range.
PrintPython program that uses range, for-loop
# This sets "i" to 0, 1 and 2.
# ... The step, not specified, is 1.
for i in range(0, 3):
print(i)
Output
0
1
2
Python program that uses range, one argument
# Use a single argument in range to start at zero.
for i in range(5):
print(f"Range(5): {i}")
Output
Range(5): 0
Range(5): 1
Range(5): 2
Range(5): 3
Range(5): 4
Then: We access the previous and current element in the list. These are adjacent elements. Please note we start the range at 1, not 0.
Python program that uses range, for-loop
names = ["mark", "michelle", "cecil"]
# Loop over range starting at index 1.
for i in range(1, len(names)):
# Adjacent names.
print(names[i - 1], names[i])
Output
mark michelle
michelle cecil
Note: The second value (0) is never reached in the loop body—it is an "exclusive" boundary.
Python program that uses range, decrements
# Loop over range with negative step.
for i in range(5, 0, -1):
print(i)
Output
5
4
3
2
1
Note: List comprehension can also be used to create lists based on expressions. It is a preferred technique.
ListPython program that creates list from range
# Create a list from a range.
values = list(range(0, 4))
print(values)
Output
[0, 1, 2, 3]
Version 1: This version of the code uses a while-loop to sum numbers 10 million times.
Version 2: Here we do the same operation as version 1, but we use a for-range loop.
Result: For performance, my tests show that a for-loop, with or without a range() call, is faster than while in Python 3.3.
Python program that times, while, for-range loop
import time
print(time.time())
# Version 1: while-loop.
c = 0
i = 0
while i < 10000000:
c += i
i += 1
print(time.time())
# Version 2: for-range loop.
c2 = 0
for y in range(0, 10000000):
c2 += y
print(time.time())
Output
1406236639.696959
1406236643.343169 while-loop: 3.65 s
1406236645.533295 for-loop, range: 2.19 s