奇怪的現象
在paython3中
print(range(10))
得出的結果是 range(0,10) ,而不是[0,1,2,3,4,5,6,7,8,9] ,為什么呢?
官網原話:
In many ways the object returned by range() behaves as if it is a list, but in fact it isn’t. It is an object which returns the successive items of the desired sequence when you iterate over it, but it doesn’t really make the list, thus saving space.
We say such an object is iterable, that is, suitable as a target for functions and constructs that expect something from which they can obtain successive items until the supply is exhausted. We have seen that the for statement is such an iterator. The function list() is another; it creates lists from iterables:
翻譯:
可以看到上面這個很奇怪,在很多種情況下,range()函數返回的對象的行為都很像一個列表,但是它確實不是一個列表,它只是在迭代的情況下返回指定索引的值,但是它並不會在內存中真正產生一個列表對象,這樣也是為了節約內存空間。
我們稱這種對象是可迭代的,或者是可迭代對象,還有一種對象叫迭代器,它們需要從一個可迭代對象中連續獲取指定索引的值,一直到索引結束。list()函數就是這樣一個迭代器,它可以把range()函數返回的對象變成一個列表。
總結:
range() 函數返回的是一個可迭代對象(類型是對象),而不是列表類型, 所以打印的時候不會打印列表。
list() 函數是對象迭代器,把對象轉為一個列表。返回的變量類型為列表。