我目前使用的版本是2.7.6

>>> help (range)
Help on built-in function range in module __builtin__:

range(...)
range(stop) -> list of integers
range(start, stop[, step]) -> list of integers

Return a list containing an arithmetic progression of integers.
range(i, j) returns [i, i+1, i+2, ..., j-1]; start (!) defaults to 0.

When step is given, it specifies the increment (or decrement).
For example, range(4) returns [0, 1, 2, 3]. The end point is omitted!
These are exactly the valid indices for a list of 4 elements.

从上文得知,range是内建函数,range(stop) 或range(start, stop[, step]) 返回的都是列表的拷贝,当列表的长度很大的时候无疑会占用很大的内存,因此,有了另一个类xrange:

>>> help(xrange)
Help on class xrange in module __builtin__:

class xrange(object)
| xrange(stop) -> xrange object
| xrange(start, stop[, step]) -> xrange object

返回的是一个xrange的对象
|
| Like range(), but instead of returning a list, returns an object that
| generates the numbers in the range on demand. For looping, this is
| slightly faster than range() and more memory efficient.

用法与range类似,但是返回的是一个对象,在循环中,因为不需要拷贝列表,因此,其执行的效率远远大与range
| Methods defined here:
|
| __getattribute__(...)
| x.__getattribute__('name') <==> x.name
|
| __getitem__(...)
| x.__getitem__(y) <==> x[y]
|
| __iter__(...)
| x.__iter__() <==> iter(x)
|
| __len__(...)
| x.__len__() <==> len(x)
|
| __reduce__(...)
|
| __repr__(...)
| x.__repr__() <==> repr(x)
|
| __reversed__(...)
| Returns a reverse iterator.
|
| ----------------------------------------------------------------------
| Data and other attributes defined here:
|
| __new__ = <built-in method __new__ of type object>
| T.__new__(S, ...) -> a new object with type S, a subtype of T

下面做一个测试:

>>> timeit.timeit('for i in range(1,1000000,1):pass',number=1)
0.11162647766673217
>>> timeit.timeit('for i in xrange(1,1000000,1):pass',number=1)
0.05531848321493271
>>>

可以看到xrange的执行效率远大于range

04-14 04:16