什么是<class'range'=“”>

时间:2016-08-31 06:05:40

标签: python python-2.7 python-3.x range

Python3:

string = range(10)
print("{}".format(type(string)))

输出:

class 'range'

我只是好奇这个课程&#39;范围&#39;。 谁能解释一下?

但是在Python2中:

输出:

class 'list'

嗯,这是自我解释

2 个答案:

答案 0 :(得分:4)

在Python 2 range(val)中生成一个列表实例,simply a function。因此type(range(10))将返回class 'list'

在Python 3中,range相当于Python 2中的xrange,它返回一个名为range的新类的实例。有关Python 2/3之间的更多更改/差异,请参阅PEP 3100

答案 1 :(得分:2)

Python 3添加了一个新的range类来有效地处理“一个不可变的数字序列”(类似于Python 2的xrange)。 Python 2没有这样的范围类,因此range函数只返回一个列表。