Because the range function was canceled in python3, and the xrange function was renamed to range, the range function can be used directly now.
Range
function description: , generate a list range([start,] stop[, step])
according start
to the stop
specified range and the step size set by step.
>>> range(10) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> range(2,10) [2, 3, 4, 5, 6, 7, 8, 9] >>> range(2,10,2) [2, 4, 6, 8] >>> type(_) <type 'list'>xrange
Function description: range
The usage of and is exactly the same, but the return is a generator.
>>> xrange(10) xrange(10) >>> xrange(2,10) xrange(2, 10) >>> xrange(2,10,2) xrange(2, 10, 2) >>> type(_) <type 'xrange'> >>> list(xrange(2, 10, 2)) [2, 4, 6, 8]
However, when you want to generate a large sequence of numbers, using xrange will have much better performance than range, because you don't need to open up a large memory space as soon as it comes up. These two are basically used when looping.
>>> r = range(0,50) >>> r [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49] >>> type(r) <type 'list'> >>> print r[0],r[49] 0 49 >>> xr = xrange(0,50) >>> xr xrange(50) >>> type(xr) <type 'xrange'> >>> print xr[0],xr[49] 0 49 >>> list(xr) == r TrueUse as much as possible in recycling
xrange
so that performance can be improved, unless you're returning a list
>>> for i in range(0,50): print i, 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 >>> for i in xrange(0,50): print i, 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49