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

后端 未结 28 2542
深忆病人
深忆病人 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:01

    Remember, use the timeit module to test which of small snippets of code is faster!

    $ python -m timeit 'for i in range(1000000):' ' pass'
    10 loops, best of 3: 90.5 msec per loop
    $ python -m timeit 'for i in xrange(1000000):' ' pass'
    10 loops, best of 3: 51.1 msec per loop
    

    Personally, I always use range(), unless I were dealing with really huge lists -- as you can see, time-wise, for a list of a million entries, the extra overhead is only 0.04 seconds. And as Corey points out, in Python 3.0 xrange() will go away and range() will give you nice iterator behavior anyway.

提交回复
热议问题