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.
(END)
以上是range函数的说明,三个参数,分别代表开始,结束位置和步长。
使用方法如下:
In [2]: range(10)
Out[2]: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] In [3]: range(1, 10)
Out[3]: [1, 2, 3, 4, 5, 6, 7, 8, 9] In [4]: range(1, 10, 2)
Out[4]: [1, 3, 5, 7, 9] In [5]: type(range(1, 3))
Out[5]: list In [6]: for i in range(10):
...: print i
...:
0
1
2
3
4
5
6
7
8
9
而xrange()说明如下:
Help on class xrange in module __builtin__: class xrange(object)
| xrange(stop) -> xrange object
| xrange(start, stop[, step]) -> xrange object
|
| 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.
|
| 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
(END)
说明了两者的区别是xrange返回的是一个可迭代的对象,range返回的则是一个列表. 同时效率更高,更快。
原因是实现的时候使用了yield(唔,源码没看见,具体对比可以看一下http://ju.outofmemory.cn/entry/122781),
因此更节省内存,规模越大区别更明显.
关于可迭代对象的定义见:https://eastlakeside.gitbooks.io/interpy-zh/content/Generators/Iterable.html
即,只要定义了可以返回一个迭代器的__iter__方法,或者__getitem__那么就是可迭代对象。
xrange使用方法如下:
In [13]: list(xrange(3))
Out[13]: [0, 1, 2] In [14]: a = xrange(3) In [15]: a.__iter__
Out[15]: <method-wrapper '__iter__' of xrange object at 0x7f415be1bdc8> In [16]: a.__iter__()
Out[16]: <rangeiterator at 0x7f415aa27210>