# Create a list from a range.
values = list(range(0, 4))
print(values)[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.
# 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.