1. 程式人生 > >Python學習筆記:python3中的range()函式的返回物件型別

Python學習筆記:python3中的range()函式的返回物件型別

在python3中

print(range(10))
range(0,10) 


得出的結果是 range(0,10) ,而不是[0,1,2,3,4,5,6,7,8,9] ,為什麼呢?

而且原來Python2版本中的xrange也已經取消。

官網原話:

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() 函式是物件迭代器,把物件轉為一個列表。返回的變數型別為列表。

參考原博地址:http://www.cnblogs.com/scofi/p/4902640.html