[Python] yield usage

Source: Internet
Author: User

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

  1. Def addlist (alist ):
  2. R = []
  3. For I in alist:
  4. R. append (I + 1)
  5. Return R

Copy code

Yield:
Python code

  1. Def addlist (alist ):
  2. For I in alist:
  3. Yield I + 1

Copy code

Of course, for this simple problem:

Python code

  1. [I + 1 for I in alist]

Copy code

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.