python3 range()函数返回的类型

Python3 range()函数返回的类型

在前几天看了range()函数,当时知道可以用for循环来遍历range函数产生的数字,还可以使用list()函数将range()函数产生的结果直接转换为列表,但是range()函数直接产生的是个什么类型呢,

print(range(1,9))
输出结果
直接输出range()函数,就是上图所示,通过type()函数print(type(range(1,9))),得到
在这里插入图片描述
通过查询,看到了别人发的一个range函数的手册描述:
官网原话:

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()函数得到的其实是一个iterable类型,在python里解释为可以迭代的对象,所以可以使用for来遍历产生的结果,使用list()将结果转化为列表类型。
原文在下面


原文:#https://blog.csdn.net/marsjhao/article/details/56853316#

猜你喜欢

转载自blog.csdn.net/qq_36930266/article/details/85219020