Iterators:
The For loop can iterate over two types of data:
1. such as list, tuple, dict, set, etc.
2. Functions with the yield keyword or can be called with __next__ (), which is the generator
The objects that can be called by for are iterable, and you can use the Isinstance method to verify that they are iterable
from collections import Iterablea =[< Span style= "COLOR: #800080" >1 , " b Span style= "COLOR: #800000", ", " c Span style= "COLOR: #800000" > " ]b ={ name ": '
So since list, tuple, dict, set and so on are all iterable, is that iterator? We can still use isinstance to judge.
from Import iteratorisinstance (a,iterator) isinstance (b,iterator)
Output Result:
False
False
It is obvious that list, set, tuple, and dict are not iterators, but they can be iterated. Can you turn them into iterators, too?
from Import Iteratora=[1,'b','C']isinstance (ITER (a ), Iterator)
Output Result:
True
Summary: List, Set, tuple, dict, etc. are iterable, but not iterator, using the ITER () method can make an iterative object into an iterator.
Let's see if the generator is iterable and iterator, and we'll use isinstance to verify it.
From collections Import Iterator
def func1 (x): while x <: = x**2 yield n x+ =1F=func1 (200)
Isinstance (F,iterator) #判断是否是迭代器
Output Result:
True
from Import iterableisinstance (f,iterable)
Output Result:
True
Summary: The generator is both iterable and iterator.
Summary: All that can be used for a loop is the iterable type.
List, dict, set, tuple, etc. are all iterable but not iterator, and can be changed to iterator by the ITER () function.
The generators are iterators.
Python non-return _ iterator