在python3中range()是这样的:
>>> range(4)
range(0, 4) #额,列表跑哪去了
在之前的python2中是这样的:
>>> range(4)
[0, 1, 2, 3] #难道range函数变了吗?
看看二者是还可以作为可迭代对象:
在python3中:
for i in range(4): print(i) 0 1 2 3 #貌似可以
再来看看python2:
>>> for i in range(4): ... print i ... 0 1 2 3 #也是可以的哈,只是换了个马甲
在python2中,range()函数会返回一个列表。
在python3中,range()函数会返回的是一个可迭代对象,但不是列表,这样做是为了节省内存空间。
但是range()的基本用法没变。
for i in range(1,10,3): print(i) 1 4 7
在pthon2中还有一个xrange(),xrange()类似range(),不过当你有一个很大范围的列表是,xrange()可能更为合适,只能在for循环中使用,在for循环外使用没有意义。