xrange仅存储范围参数并按需生成数字。然而,Python的C实现目前将其args限制为C long s:
xrange(2**32-1, 2**32+1) # When long is 32 bits, OverflowError: Python int too large to convert to C longrange(2**32-1, 2**32+1) # OK --> [4294967295L, 4294967296L]
$ python -m timeit 'for i in range(1000000):' ' pass'10 loops, best of 3: 90.5 msec per loop$ python -m timeit 'for i in xrange(1000000):' ' pass'10 loops, best of 3: 51.1 msec per loop
import time
for x in range(1, 10):
t = time.time()[v*10 for v in range(1, 10000)]print "range: %.4f" % ((time.time()-t)*100)
t = time.time()[v*10 for v in xrange(1, 10000)]print "xrange: %.4f" % ((time.time()-t)*100)
$ python -m timeit "for i in xrange(10111):" " for k in range(100):" " pass"10 loops, best of 3: 59.4 msec per loop
$ python -m timeit "for i in xrange(10111):" " for k in xrange(100):" " pass"10 loops, best of 3: 46.9 msec per loop
>>> print range.__doc__range(stop) -> list of integersrange(start, stop[, step]) -> list of integers
Return a list containing an arithmetic progression of integers.range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.When step is given, it specifies the increment (or decrement).For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!These are exactly the valid indices for a list of 4 elements.
>>> print xrange.__doc__xrange(stop) -> xrange objectxrange(start, stop[, step]) -> xrange object
Like range(), but instead of returning a list, returns an object thatgenerates the numbers in the range on demand. For looping, this isslightly faster than range() and more memory efficient.
python3.5.2
>>> print(range.__doc__)range(stop) -> range objectrange(start, stop[, step]) -> range object
Return an object that produces a sequence of integers from start (inclusive)to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.These are exactly the valid indices for a list of 4 elements.When step is given, it specifies the increment (or decrement).
>>> print(xrange.__doc__)Traceback (most recent call last):File "<stdin>", line 1, in <module>NameError: name 'xrange' is not defined