A function that contains the yield expression is a special function called a generator function. When called, an iterator is returned ), you can use next or send (MSG) for the call ). Its usage is similar to return. The difference is that it remembers the status of the last iteration and continues execution.
The difference between send (MSG) and next () Is that send can pass parameters to the yield expression, and the passed parameters will be used as the value of the yield expression, the yield parameter is the value returned to the caller. The initial call must start with next () or send (none); otherwise, an error is returned.
For example:
First generate an iterator F, F. Next () will execute the generator function to yield, generate a value, and then suspend.
Then, F. Next () or F. Send (MSG) will return the value in the generator function, execute it to the next yield, and then suspend the generated value.
Then, F. Next () or F. Send (MSG) will return values in the generator function, and the intent is to execute to the next yield, but there is no yield later, so an exception is thrown.
Yield can effectively simplify code and reduce space waste.
For example, each element in the list is + 1.
Traditional writing:
Python code
- Def addlist (alist ):
- R = []
- For I in alist:
- R. append (I + 1)
- Return R
Copy code
Yield:
Python code
- Def addlist (alist ):
- For I in alist:
- Yield I + 1
Copy code
Of course, for this simple problem:
Python code
- [I + 1 for I in alist]
Copy code