There are several types of data that are used directly for a For loop:
1. Data type of collection class: List tuple dict set STR, etc.
2. Generator generator, including generator and generator function with yiled
These objects, which can be used directly for the for loop, are called iterative object iterable.
1 #Coding=utf-82 3 fromCollectionsImportiterable4 5 Print(Isinstance ({}, iterable))#True6 Print(Isinstance ([], iterable))#True7 Print(Isinstance ('iterable', iterable))#True8 Print(Isinstance ((), iterable))#True9 Print(Isinstance (iterable))#False
Iterator: An iterator (Iterator) that can be called by next () to continually return the next value.
1 fromCollectionsImportIterator2 3 Print(Isinstance ({}, Iterator))#False4 Print(Isinstance ([], Iterator))#False5 Print(Isinstance ('iterable', Iterator))#False6 Print(Isinstance ((), Iterator))#False7 Print(Isinstance (x forXinchRange (5)), Iterator))#True8 9 #as noted above, lists, dictionaries, strings, ganso, etc. are not iterators (Iterator)
Can an iterative object become an iterator? The pass-Multiple built-in method ITER () can achieve
1 fromCollectionsImportIterator2 3 Print(Isinstance (ITER ({}), Iterator))#True4 Print(Isinstance (ITER ([]), Iterator))#True5 Print(Isinstance (ITER ('iterable'), Iterator))#True6 Print(Isinstance (ITER (()), Iterator))#True7 Print(Isinstance (x forXinchRange (5)), Iterator))#True
Summary:
1 #the nature of the for loop of Python is that it is continuously implemented by invoking the next function, such as the following two-segment code2 3 #Code One4 5 forXinchRange (10):6 Print(x)7 8 #Code two9it = iter ([0, 1, 2, 3, 4, 5, 6, 7, 8, 9])Ten whileTrue: One Try: Ax =Next (IT) - Print(x) - exceptstopiteration: the Break - #code one is equivalent to code two
Python path----------iterator