What is the difference between range and xrange functions in Python 2.X?

后端 未结 28 2041
深忆病人
深忆病人 2020-11-22 03:14

Apparently xrange is faster but I have no idea why it\'s faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about

相关标签:
28条回答
  • 2020-11-22 04:16

    You will find the advantage of xrange over range in this simple example:

    import timeit
    
    t1 = timeit.default_timer()
    a = 0
    for i in xrange(1, 100000000):
        pass
    t2 = timeit.default_timer()
    
    print "time taken: ", (t2-t1)  # 4.49153590202 seconds
    
    t1 = timeit.default_timer()
    a = 0
    for i in range(1, 100000000):
        pass
    t2 = timeit.default_timer()
    
    print "time taken: ", (t2-t1)  # 7.04547905922 seconds
    

    The above example doesn't reflect anything substantially better in case of xrange.

    Now look at the following case where range is really really slow, compared to xrange.

    import timeit
    
    t1 = timeit.default_timer()
    a = 0
    for i in xrange(1, 100000000):
        if i == 10000:
            break
    t2 = timeit.default_timer()
    
    print "time taken: ", (t2-t1)  # 0.000764846801758 seconds
    
    t1 = timeit.default_timer()
    a = 0
    for i in range(1, 100000000):
        if i == 10000:
            break
    t2 = timeit.default_timer() 
    
    print "time taken: ", (t2-t1)  # 2.78506207466 seconds
    

    With range, it already creates a list from 0 to 100000000(time consuming), but xrange is a generator and it only generates numbers based on the need, that is, if the iteration continues.

    In Python-3, the implementation of the range functionality is same as that of xrange in Python-2, while they have done away with xrange in Python-3

    Happy Coding!!

    0 讨论(0)
  • 2020-11-22 04:16

    It is for optimization reasons.

    range() will create a list of values from start to end (0 .. 20 in your example). This will become an expensive operation on very large ranges.

    xrange() on the other hand is much more optimised. it will only compute the next value when needed (via an xrange sequence object) and does not create a list of all values like range() does.

    0 讨论(0)
  • 2020-11-22 04:16

    See this post to find difference between range and xrange:

    To quote:

    range returns exactly what you think: a list of consecutive integers, of a defined length beginning with 0. xrange, however, returns an "xrange object", which acts a great deal like an iterator

    0 讨论(0)
  • 2020-11-22 04:17

    range :-range will populate everything at once.which means every number of the range will occupy the memory.

    xrange :-xrange is something like generator ,it will comes into picture when you want the range of numbers but you dont want them to be stored,like when you want to use in for loop.so memory efficient.

    0 讨论(0)
提交回复
热议问题