range和xrange的区别

时间:2023-03-08 16:03:56

range和xrange的区别

python3里面只有range,返回结果是一个生成器,官方文档是这样描述的

class range(object):
"""
range(stop) -> range object
range(start, stop[, step]) -> range object Return an object that produces a sequence of integers from start (inclusive)
to stop (exclusive) by step. range(i, j) produces i, i+1, i+2, ..., j-1.
start defaults to 0, and stop is omitted! range(4) produces 0, 1, 2, 3.
These are exactly the valid indices for a list of 4 elements.
When step is given, it specifies the increment (or decrement).
"""
def count(self, value): # real signature unknown; restored from __doc__
""" rangeobject.count(value) -> integer -- return number of occurrences of value """
return 0 def index(self, value, start=None, stop=None): # real signature unknown; restored from __doc__
"""
rangeobject.index(value, [start, [stop]]) -> integer -- return index of value.
Raise ValueError if the value is not present.
"""
return 0

range有两个方法,count和index
- count(value) 统计元素出现的次数
- index(value) 返回元素的索引
```python
a = range(10)

print(a.count(8)) # 1

print(a.index(5)) # 5


<br>
python2里面range分为range和xrange range返回一个列表,而xrange返回一个生成器 python2关于xrange的定义
```python
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.
"""
def __getattribute__(self, name): # real signature unknown; restored from __doc__
""" x.__getattribute__('name') <==> x.name """
pass def __getitem__(self, y): # real signature unknown; restored from __doc__
""" x.__getitem__(y) <==> x[y] """
pass def __init__(self, stop): # real signature unknown; restored from __doc__
pass def __iter__(self): # real signature unknown; restored from __doc__
""" x.__iter__() <==> iter(x) """
pass def __len__(self): # real signature unknown; restored from __doc__
""" x.__len__() <==> len(x) """
pass @staticmethod # known case of __new__
def __new__(S, *more): # real signature unknown; restored from __doc__
""" T.__new__(S, ...) -> a new object with type S, a subtype of T """
pass def __reduce__(self, *args, **kwargs): # real signature unknown
pass def __repr__(self): # real signature unknown; restored from __doc__
""" x.__repr__() <==> repr(x) """
pass def __reversed__(self, *args, **kwargs): # real signature unknown
""" Returns a reverse iterator. """
pass

range与xrange的比较
```python
a = range(5)
b = xrange(10)

print a, type(a)

print b, type(b)

print b[2] # 2

print b[3] # 3

print b[4] # 4

print len(b)

for i in reversed(b):

print i

<br>
运行结果
```python
[0, 1, 2, 3, 4] <type 'list'>
xrange(10) <type 'xrange'>
2
3
4
10
9
8
7
6
5
4
3
2
1
0

## 小结
- 只有在python2中才分range和xrange,python3只有range
- python2里面range返回一个列表,xrange返回一个类似生成器的xrange对象
- xrange对象的用法与列表一样,但是只是在取值时在占用内存空间(这一点类似于python3的range)