The Python3 iterator and generator iterations are one of the most powerful features of Python and a way to access the elements of a collection.
An iterator is an object that remembers where to iterate. The iterator object is accessed from the first element of the collection until all the elements have been accessed and finished.
Iterators can only move forward and not back.
There are two basic methods for iterators: ITER () and next ().
A string, a list, or a tuple object can be used to create iterators in Python, functions that use yield are called generators (generator).
Unlike a normal function, the generator is a function that returns an iterator that can only be used for iterative operations, and simpler to understand that the generator is an iterator.
During the call to the generator, the function pauses and saves all current running information, returns the value of the yield, and continues from its current position the next time the next () method is executed, each time the yield is encountered.
Invokes a generator function that returns an Iterator object. """ImportSYS #迭代器 list = [1,2,3,4,5,6] Print (' for traversal iterator ') Iter1 = iter (list) forX inIter1:print (x) Print (' whike traversal iterator ') Iter2 = iter (list)While True:Try: Print (Next (iter2), end=" , ")exceptStopiteration:print ("Iterator exception") Break #生成器defFibonacci (N): # generator Function-Fibonacci A, B, counter = 0, 1, 0While True:if(Counter > N): returnyieldA A, B = B, A + b counter + = 1 F = Fibonacci (Ten) # F is an iterator that is returned by the generator to generateWhile True:Try: Print (Next (f), end=" ")exceptStopIteration:sys.exit ()