Python range() 與xrange()的區別
阿新 • • 發佈:2019-01-03
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(start, stop[, step])
例如:
In [4] : range(5)
Out[4]: [0, 1, 2, 3, 4]
In [5]: type(range(5))
Out[5]: list
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
xrange()函式返回的是一個生成器,函式形式為xrange(start, stop[, step])
例如:
In [6]: xrange(5)
Out[6]: xrange(5)
In [7]: type(xrange(5))
Out[7]: xrange
在迴圈中需要生成一個很大的序列時,儘量使用xrange(),該函式不用一上來就申請很大的空間在儲存元素,大大的節省的空間。
而range()直接生成一個列表,需要很大的空間來儲存,沒有使用xrange()好。