How to use yield in python

Source: Internet
Author: User

Today, when reading code from other colleagues, I found a python keyword that has never been used: yield.

I first asked my colleague, and heard him say a few words. I had a vague impression that it was just fuzzy. So I searched for the information myself. After reading for a long time, I gradually became clear. However, I am still confused about the working mechanism and application. Well, write down the initial impression.

Yield is simply a Generator ). The generator is a function that remembers the position in the function body during the last return. The second (or NTH) Call to the generator function jumps to the center of the function, while all local variables in the last call remain unchanged.

You can see that a function contains yield, which means that this function is already a Generator and its execution will be much different from other common functions.

You may be confused here. Let's take a look at some instances first:
Copy codeThe Code is as follows:
Def test (data_list ):

For x in data_list:

Yield x + 1

Data = [1, 2, 4]

For y in test (data ):

Print y

The output result is:

2 3 4 5

Another usage:

Handle = test (data)

Handle. next () Output 2

Handle. next () Output 3

Handle. next () output 4

Handle. next () Output 5

Handle. next () will report an error

This is just the initial impression of yield.

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.