The difference between xrange and range in python

  • 2020-04-02 13:38:05
  • OfStack

Range ([start,] stop[, step]), generate a sequence according to the range specified by start and stop and the step size set by step.
The range of sample:

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

Xrange is the same as range except that instead of an array, a generator is generated.
Xrange example:

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

From the above example, we can know that when generating a large number sequence, xrange is much better than range in performance, because we don't need to open up a large amount of memory space at the beginning. Both of them are basically used during the loop:


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

The results of these two outputs are the same, in fact, there are many differences, range will directly generate a 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 a list directly, xrange returns one of the values per call:

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

Output results:

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


Related articles: