Python 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):
One argument. When we use just one argument in range() the start is considered zero. So a range 5 goes from 0 through 4 inclusive.Literal: F
Python program that uses range, one argument# Use a single argument in range to start at zero.
for i in range(5):
Adjacent. Often we need to access adjacent list elements. One way to do this is with range(). In this example, we loop through all the indexes in the list.
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])
Range, negative. We can use range() to decrement a variable, to move downwards. We specify the "step" value as the optional third parameter of range. We use -1 to decrement by one.
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):
Create list. We can use range() to create a list based on a sequence of values. This is much simpler than looping and adding numbers—it is shorter, less prone to bugs.
Note: List comprehension can also be used to create lists based on expressions. It is a preferred technique.
Python program that creates list from range# Create a list from a range.
values = list(range(0, 4))
[0, 1, 2, 3]
A benchmark. What performance impact does range() have? With range, we provide two or three numbers and loop over them. I found that range loops are faster than while-loops.
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
# Version 1: while-loop.
c = 0
i = 0
while i < 10000000:
c += i
i += 1
# Version 2: for-range loop.
c2 = 0
for y in range(0, 10000000):
c2 += y
1406236643.343169 while-loop: 3.65 s
1406236645.533295 for-loop, range: 2.19 s
With range(), we keep our code simple. And in the benchmark, we found that range() does not cause any performance problems. It is faster than many alternatives.
An immutable sequence. In the Python documentation, range() is considered an "immutable sequence." This means it cannot be changed after specified.
An optimization. Because range() is immutable, it can be heavily optimized—no allocations in memory are needed for a new range. With simpler, faster code, range is a good choice.