Iterator iterator
- iterative Protocols -as long as the __iter__ method is included, it is an iterative iterable
- iterator Protocol -an iterator that internally contains the __next__ method and the __iter__ method
- As long as the data type can be used for loop, it must have the __iter__ method, the for loop is actually using an iterator
- You can iterate as long as you have an iterator
- An iterator object. __iter__ () = = Iterator
- The __next__ () method in the iterator can get the value one by one
An iterator object can be traversed using a regular for statement:
list=[1,2,3,4= iter (list) # Create iterator object for in it: Print (x, end="")
Execute the above procedure, the output result is as follows:
1 2 3 4
Benefits of Iterators
- A value from one of the container types will take all the values
- Saves memory space
Generator
Generator functions are essentially functions that we write ourselves.
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 each time the yield is encountered, returning the value of yield. and continue running from the current location the next time the next () method is executed.
Yield keyword
The yield keyword and return usage are the same, as long as the function containing the yield keyword is a generator function, yield needs to be written inside the function, can not be used in conjunction with return, the generator function will be executed after a generator as a return value
def generator (): Print (1) yield ' a ' # generator function: After execution, you get a generator as the return value ret = generator ()print(ret)print( Ret.__next__())
#Wahaha%idefWahaha (): forIinchRange (2000000): yield 'Wahaha%s'%icount=0 forIinchG:count+=1Print(i)ifCount > 50: Break forIinchG:count+=1Print(i)ifCount > 100: Break
Learn python-functions (iterators, generators)