pytthon-range 返回的是一个可迭代的object

内容

A strange thing happens if you just print a range:

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

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:

>>>
>>> list(range(5))
[0, 1, 2, 3, 4]

Later we will see more functions that return iterables and take iterables as argument.

总结

range返回的是一个可迭代的object,目的是节省内存。可通过list()进行类型转化。

猜你喜欢

转载自blog.csdn.net/qq_29007291/article/details/82259984