On the differences between range and xrange in Python

  • 2020-06-19 10:45:04
  • OfStack

The & # 65279; range() is a built-in function of Python that creates a list of integers that can be incremented or decremented. xrange does the same thing, and today we'll look at the differences.

range function description: range([start,] stop[, step]) generates 1 sequence according to the range specified by start and stop and the step size set by step.

range example:


>>> range(6)
[0, 1, 2, 3, 4, 5]
>>> range(1,6)
[1, 2, 3, 4, 5]
>>> range(0,6,2)
[0, 2, 4]

xrange function description: the usage is exactly the same as range, except that instead of generating an array, it generates a generator.

Special note: the xrange function has been cancelled in Python3. In python3, the implementation of range() has been removed, leaving the implementation of xrange() and renaming xrange() to range(). So Python3 cannot use xrange, only range

xrange example:


>>> xrange(6)
xrange(6) #  Note: The sum output here range Is different after ather 
>>> list(xrange(6))
[0, 1, 2, 3, 4, 5]
>>> xrange(1, 6)
xrange(1, 6)
>>> list(xrange(1, 6))
[1, 2, 3, 4, 5]
>>> xrange(0,6,2)
xrange(0, 6, 2)
>>> list(xrange(0, 6, 2))
[0, 2, 4]

As you can see from the above example, xrange performs much better than range when generating large number sequences because it does not require a large block of memory upfront. Both are basically used during loops:


for i in range(0, 100):
  print i
for i in xrange(0, 100):
  print i

The two outputs are the same, but there are actually a lot of differences. range will directly generate an list object:


a = range(0,100)
print type(a)
print a
print a[0], a[1]

Output results:

< type 'list' >
[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, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99]
0 1

Instead of generating one list directly, xrange returns one value per call:


a = xrange(0,100)
print type(a)
print a
print a[0], a[1]

The results are as follows:

< type 'xrange' >
xrange(100)
0 1

Finally, once again, Python3 has eliminated the xrange method, just use range!


Related articles: