Last Updated: February 25, 2016
·
715
· gurpinars

range or xrange?

range() and xrange() are built-in functions in python-using similarly.Their difference is that you get an list object if you use range() and using xrange(),you get an xrange object.what does it mean?
in python-docs:

This is an opaque sequence type which yields the same values as the corresponding list, without actually storing them all simultaneously.

The advantage of the xrange type is that an xrange object will always take the same amount of memory, no matter the size of the range it represents.

an example:

import time

def range_i():
    start = time.time()
    sum = 0
    for i in range(1,10000):
        sum += i
    print "range:%f s"%(time.time()-start)
def xrange_i():
    start = time.time()
    sum = 0
    for i in xrange(1,10000):
        sum += i
    print "xrange:%f s"%(time.time()-start)

range_i()
xrange_i()

output:

range:0.000848 s 
xrange:0.000540 s 

So if we need an list on memory, we should use range() but just for iterating,we should use xrange.Thus, we get a little increase in performance.