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

显然xrange更快,但我不知道为什么它更快(除了迄今为止的轶事更快),或者除此之外还有什么不同

for i in range(0, 20):
for i in xrange(0, 20):

range creates a list, so if you do range(1, 10000000) it creates a list in memory with 9999999 elements.

xrange is a sequence object that evaluates lazily.

It should be added from @Thiago's hint, that in python3, range does the equivalent of python's xrange


range creates a list, so if you do range(1, 10000000) it creates a list in memory with 9999999 elements.

xrange is a generator, so it is a sequence object is a that evaluates lazily.

This is true, but in Python 3, range will be implemented by the Python 2 xrange(). If you need to actually generate the list, you will need to do:

list(range(1,100))

Remember, use the timeit module to test which of small snipps 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 behaviour anyway.

链接地址: http://www.djcxy.com/p/4098.html

上一篇: 循环使用枚举或在Python中使用xrange循环更快?

下一篇: Python 2.X中的range和xrange函数有什么区别?