range()函数
结论:python3的range函数相当于python2的xrange函数,python3中没有xrange函数。
对比返回值:python2的xrange函数返回的是xrange类型,而range函数返回的是list类型,所以内存将会分布相应的长度的空间给list
优缺点:python2的xrange和python3的range函数返回的是一个对象,没有将数据完全实例化,所以内存中只有一个对象的空间,对性能优化还是很有帮助
验证过程:
在python3的builtins.py文件中定义了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).
"""
返回也是
Python 3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:44:43)
[Clang 6.0 (clang-600.0.57)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print(type(range(8)))
<class 'range'>
python2的__bulitin__.py中定义了range方法,返回的是实例化的list
def range(start=None, stop=None, step=None): # known special case of 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.
"""
pass
输出
Python 2.7.16 (default, Sep 2 2019, 11:59:44)
[GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.46.4)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print(type(xrange(8)))
<type 'xrange'>
>>> print(type(range(8)))
<type 'list'>
注意:像python3将实例化的类型改成对象有很多,如字典中的items
Python3
>>> import sys
>>> print(sys.version)
3.7.2 (v3.7.2:9a3ffc0492, Dec 24 2018, 02:44:43)
[Clang 6.0 (clang-600.0.57)]
>>> a= {'a':1}
>>> type(a.items())
<class 'dict_items'>
python2
>>> import sys
>>> print(sys.version)
2.7.16 (default, Sep 2 2019, 11:59:44)
[GCC 4.2.1 Compatible Apple LLVM 10.0.1 (clang-1001.0.46.4)]
>>> a = {'a':1}
>>> print(type(a.items()))
<type 'list'>