python 中range与xrange的区别

时间:2022-05-17 22:48:30
python 中range与xrange的区别

先来看看range与xrange的用法介绍

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.

实例说明
eg:
In [4]: range(6)
Out[4]: [0, 1, 2, 3, 4, 5]

In [5]: range(1,6)
Out[5]: [1, 2, 3, 4, 5]

In [6]: range(1,6,1)
Out[6]: [1, 2, 3, 4, 5]

In [7]: range(1,6,2)
Out[7]: [1, 3, 5]

range()返回的是list对象(列表),默认步长为1,一次性输出所有内容

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

In [15]: xrange(5)
Out[15]: xrange(5)

In [16]: list(xrange(5))
Out[16]: [0, 1, 2, 3, 4]

In [17]: list(xrange(1,5))
Out[17]: [1, 2, 3, 4]

In [18]: list(xrange(0,6,2))
Out[18]: [0, 2, 4]

range() 与xrange()都用于循环
In [24]: for i in range(10,20):
....: print i
....:
10
11
12
13
14
15
16
17
18
19

In [25]: for i1 in xrange(10,20):
....: print i1
....:
10
11
12
13
14
15
16
17
18
19

这两个输出的结果都是一样的,实际上有很多不同,range会直接生成一个list对象,xrange直接生成一个生成器:

通过上面的示例知道:要生成很大的数字序列的时候,用xrange会比range性能优很多,因为不需要一开始就开辟一块很大的内存空间

所以xrange做循环的性能比range好,尤其是返回很大的时候。尽量用xrange吧,除非你是要返回一个列表。