首页 > 编程语言 >Python - Iterator vs Iterable

Python - Iterator vs Iterable

时间:2024-07-31 09:38:59浏览次数:9  
标签:function iterator Python iter will returns vs Iterable iterable

There are many built-in functions and methods that return iterables and iterators. Here are a few examples:

range() returns an iterable

dict.keys() returns an iterable

dict.items() returns an iterable

dict.values() returns an iterable

enumerate() returns an iterator

zip() returns an iterator

reversed() returns an iterator

open() returns an iterator

map() returns an iterator

filter() returns an iterator

Some of the functions and methods return iterables, and some return iterators. We need to know the type of object that we are dealing with (iterable or iterator), otherwise we will get unexpected results. Let us see why it is so.

We know that after an iterator is exhausted, it raises a StopIteration exception each time next is called on it. There is no way to reset or restart an iterator. If you need to iterate over the same data stream again, then you will have to create a new fresh iterator by calling iter function over the iterable from which you got the iterator.

So, an iterator becomes a useless throw-away object once it is exhausted. It is not possible to reset or restart an iterator. You need to get a fresh iterator if you need to iterate again. The iteration tools that we have seen in the previous section, work internally by calling iter on the iterable and so they get a fresh iterator automatically.

Suppose we have an iterable x and we use it in these 3 iteration contexts:

for i in x:

pass

L = list(x)

n = max(x)

All these iteration tools will call iter on the iterable, get fresh iterators, and will use those iterators. This code will work as expected, and there is no problem here.

Now suppose we have an iterator y. You know that iterators can respond to the iter function, which can be used in any iteration context. So, we use this iterator y in the same three places:

for i in y:

pass

L = list(y)

n = max(y)

The for loop will work as expected, but the next two statements will not work as expected and they will not show any error also. This is because when an iterator is passed through the iter() function, you get the same iterator back. The for loop exhausted the iterator y, and when the list function called iter function on y, it got the same exhausted iterator back. When it called the next function on the exhausted iterator, a Stopiteration error was raised, which was caught. Similarly, in the last statement, when iter will be called on y, y will be only returned which is already exhausted. An exhausted iterator is like an empty container.

From these three iteration contexts, whichever is written first will work, and the other two will not work. If you write the max function before the for loop and list function, then the max function will work but the other two will not work, because in that case the max function will consume the iterator and the other two will get the exhausted iterator.

So, you can iterate many times over an iterable, but you can iterate only once over an iterator.

This is because when an iterable is passed to iter function, it returns a fresh iterator while when an iterator is passed to iter function it returns the same iterator.

If a function returns an iterable object, then that object supports multiple iterations, while the iterator objects support just one iteration. This is because an iterable can be used to get a fresh iterator every time iter is used on it. But for an iterator, the same iterator will be returned every time iter is used on it. 

 

 

标签:function,iterator,Python,iter,will,returns,vs,Iterable,iterable
From: https://www.cnblogs.com/zhangzhihui/p/18333904

相关文章

  • 在python中使用变量引用Panda列名称
    我正在尝试编写一个函数来简化我的代码,因此我传递了包含列名称的变量。它适用于Django应用程序,调试器不会对我的错误所在提供任何反馈,只是“内部服务器错误”。我的代码工作正常,不是作为函数编写的:df_trips['trip_time_prep_starts']=df_trips["trip_time_prep_sta......
  • 如何在 Pyqt5 Python 中实现 QTableWidget 列过滤器中的搜索栏?
    我使用pyqt5创建了一个QTableWidget,并成功地在表格小部件的每一列中添加了过滤选项,并使用堆栈溢出上可用的答案之一。过滤器按预期工作,但我想在顶部的过滤器中添加搜索栏来搜索值。在我的python脚本中,过滤器中可能有大约50多个唯一值。因此,如果有一种方法可以在过滤器......
  • Python - Abstract Base classes
    Wehaveseenthatifwehavetodefineagroupofclassesthathavesimilarfeaturesandshowcommonbehavior,wecandefineabaseclassandtheninherittheclassesfromit.Inthederivedclasses,wehavethechoicetoeitherusethebaseclassversion......
  • python3 unittest+BeautifulReport单个进程输出多个测试报告
    最近一个项目中需要由于输出的案例内容非常多(上万条),导致BeautifulReport输出的报告内容非常大(几百兆)。浏览器无法正常处理这么大的测试报告,就算打开了,也不方便阅读和处理,因此需要将报告分成多个输出。经修改代码,发现单个进程内输出多个测试报告出现问题:第一个测试报告能正常数据......
  • 具有自引用的类装饰器的 Python 类型提示
    我的最终目标是编写一个系统来轻松记录函数调用(特别是类方法)。我首先编写一个带有包装方法的类Loggable,该方法允许我装饰子类方法并记录它们的调用|||现在我可以编写子类并记录它们的调用:Param=ParamSpec("Param")RetType=TypeVar("RetType")CountType=......
  • 如何在for循环中使用curve_fit函数在python中一次性创建多个回归?
    简而言之,我有两个矩阵,一个称为t,另一个称为y。每个都有7列。假设它们被称为a、b、c、d、e、f和g。我想要的是从a对a、b对b、...、g对g这两个矩阵进行回归。我已经设法使我的算法使用curve_fit对一列进行回归一次。但我真正希望的是它能够一次性完成7个回归......
  • 激活虚拟环境会让python消失?
    VisualStudioCode终端的屏幕截图如屏幕截图所示,python在Powershell中运行得很好。然后我在E:\DrewFTCAPI\ftcapivenv激活虚拟环境,然后python就消失了。不仅没有消失,它不运行任何东西,也不产生任何输出。我至少预计会出现某种类型的"python"i......
  • Python 3.6 中的相互递归类型,使用命名元组语法
    我正在尝试实现图的节点和边。这是我的代码:fromtypingimportNamedTuple,ListclassNode(NamedTuple):name:stredges:List[Edge]classEdge(NamedTuple):src:Nodedest:Node这会引发错误,因为创建Edge时未定义Node类型。......
  • 使用 keras 模型对函数进行 Python 类型提示
    如果我创建这样的函数:defmdl(input_shape):model=Sequential()model.add(Conv2D(depth=64,kernel_size=(3,3),input_shape=input_shape,activation='relu'))model.add(Dense(32),activation='relu')model.add(Dropout(0.3))m......
  • Python:自动完成可以用于列表中的元素吗?
    Python在函数参数和函数返回类型中具有类型提示。类的元素是否有类似的东西?我希望能够在如下示例中使用自动完成功能:classMyClass:defhello(self):print("Hello")mylist=[]mylist.append(MyClass())foriinmylist:i.hello()#Noautocomplete......