Iterators
Iteration is one of the most powerful features of Python and is a way to access the elements of a collection.
An iterator is an object that you can remember to traverse a position.
The iterator is accessed from the first element of the collection until all the elements have been accessed and finished. Iterators can only move forward without backing back.
There are two basic methods of iterators: ITER () and Next ()
A string, list, or tuple object can be used to create iterators.
Iterator objects can be traversed using a regular for statement
You can also use the next () function
Generator
In Python, a function that uses yield is called a generator (generator).
Unlike a normal function, a generator is a function that returns an iterator that can be used only for iterative operations, and simpler to understand that the generator is an iterator.
In the process of calling the generator to run, the function pauses and saves all current run information, returns the value of yield, and continues running from its current location the next time the next () method is executed, each time yield is encountered.
Invokes a generator function that returns an Iterator object.
Compared with yield and not the case
Yield execution Results
No yield execution results
Under what circumstances will yield be used?
A function f,f returns a list, which is dynamically computed (either mathematically or logically, and the list is large (either fixed or enlarged with the increase in input parameters), and this is the time at which the It is useful to have a single list element instead of a complete list to save memory each time we call this function and use an iterator to loop it.
Python3 iterators and generators